基于JavaWeb文件上传与下载功能

单文件上传

首页页面端(upload.html)

服务端处理(UploadServlet.java)

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

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

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置请求编码
        request.setCharacterEncoding("utf-8");
        //获取服务端用于存储文件的目录
        String baseDir = request.getServletContext().getRealPath("myfile");
        //获取一个文件单元
        Part part = request.getPart("myfile");
        String type = part.getContentType();
        long size = part.getSize();
        String fname = part.getSubmittedFileName();

        System.out.println("文件名称:" + fname);
        System.out.println("文件类型:" + type);
        System.out.println("文件大小:" + size);
	    //存储到服务器
        part.write(baseDir + File.separator + fname);

    }
}

**

多文件上传

前端页面端设置


服务端处理

@WebServlet("/upload2")
@MultipartConfig(
			fileSizeThreshold=1024*1024,	//设置内存缓存的最大空间(当上传文件的字节数达到该值后使用临时文件缓存)
			location="d:/temp",				//设置临时文件的存储目录
			maxFileSize=1024*1024*200,		//设置允许上传的单个文件的最大限制
			maxRequestSize=1024*1024*500	//设置表单允许提交的总字节数
		)
public class UploadServlet2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
  
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");
		String base = request.getServletContext().getRealPath("myfile");
		//获取所有上传的附件信息
		Collection parts = request.getParts();
		parts.forEach(part->{
			
			String fname = part.getSubmittedFileName();
			String type = part.getContentType();
			long size = part.getSize();
			System.out.println("文件名:"+fname);
			System.out.println("文件类型:"+type);
			System.out.println("文件大小:"+size); 
			
			try {
				part.write(base+File.separator+fname);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		});
	}
}

**

你可能感兴趣的:(代码实现)