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

单文件上传

首页页面端(upload.html)

<form action="upload" method="post" enctype="multipart/form-data">
    <input type="file" name="myfile"/>
    <button>上传</button>
</form>

服务端处理(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);

    }
}

**

多文件上传

前端页面端设置

<form action="upload" method="post" enctype="multipart/form-data">
    <input type="text" name="fname" placeholder="请输入文件名" /> <br />
    <input type="file" name="myfile" multiple/>
    <button>上传</button>
</form>

服务端处理

@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<Part> 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();
			}
			
		});
	}
}

**

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值