html/jsp上传文件到服务器

需要导入:jar包

html/jsp代码

form表单中method必须设置为post,并且要设置enctype=”multipart/form-data”,要提交的inpu标签要设置name属性

				
文件:

servlet代码

    import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "HeadServlet",urlPatterns = "/HeadServlet")
public class HeadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        //临时文件/解析工厂
        DiskFileItemFactory head = new DiskFileItemFactory();
        //解析器
        ServletFileUpload upload = new ServletFileUpload(head);
        //判断form属性enctype的值是否为multipart/form-data
       try {
           //用pasreRequest将请求的值封装成fileItem对象然后放在fileItems中
           List fileItems = upload.parseRequest(request);
           FileItem fileItem = fileItems.get(0);
           String fileName = fileItem.getName();
           File file = new File("E:\\上传的文件\\" + fileName);
           fileItem.write(file);
       }catch (Exception e){

       }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request,response);
    }
}

演示

html/jsp上传文件到服务器_第1张图片

你可能感兴趣的:(JS,javaWeb)