JavaWeb-文件下载和上传

文件上传与下载

大家经常使用百度网盘来上传自己的学习资料、视频、小电影什么的,那它是如何做到的呢?我们知道如何提交文本、下拉框、复选框,那如何提交一个文件呢?

1、上传

在Servlet2.5中,我们要实现文件上传功能时,一般情况下都需要借助其他开源组件。然而在Servlet3.0中提供了对文件上传的直接支持,不需要借助任何第三方上传组件,直接使用Servlet3.0提供的API就能够实现文件上传功能了。

1、设置表单的enctype=“multipart/form-data”,methos必须为post

<form action="${pageContext.request.contextPath}/UploadServlet" method="post"  enctype="multipart/form-data"  >
	上传:<input type="file" name="uploadFile1" />  <br/><br/>
	上传:<input type="file" name="uploadFile2" />  <br/><br/>
	上传:<input type="file" name="uploadFile3" />  <br/><br/>
	<input type="submit"  />
</form>

2、在servlet中加上@MultipartConfig注解(文件上传是后来加入的技术,所以需要申明一下)

3、在servlet中使用request.getPart(“参数名”)获取单个文件或request.getParts()获取上传的文件的集合。

4、通过part.getHeader(“content-disposition”);或者String fileName = p.getSubmittedFileName();(tomcat8)来获取文件名和后缀。文件名为中文的时候需要加上request.setCharacterEncoding(“utf-8”);才会不乱码。

5、通过part.write(filePath+fileName);将文件写到本地指定目录中。

@MultipartConfig
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
	
	private String filePath = "D:\\proFile\\" ;
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		
		Collection<Part> parts = req.getParts();
		for (Part p : parts) {
			if(p!=null){
				String fileName = p.getSubmittedFileName();
				p.write(filePath+fileName);
			}
		}
	}

}

2、下载

		//设置请求编码为utf-8
		req.setCharacterEncoding("utf-8");
		//获取需要下载的文件名
		String fileName = req.getParameter("fileName");
		//查看下载文件是否存在
		File file = new File(path + fileName);
		if (!file.exists()) {
			System.out.println("文件不存在");
			return;
		}
		
		
		//告诉http协议,这是一个文件流,请下载它
		res.setContentType("application/octet-stream");
		
		//告诉http协议,文件名是啥
		res.addHeader("Content-Disposition","attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso-8859-1"));
		//告诉http协议,文件是多大
		res.addHeader("Content-Length", file.length() + "");
		
		//打开一个输入流,指向目标文件
		FileInputStream in = new FileInputStream(file);
		//in.available() 获取输入流目标的大小
		byte[] data = new byte[in.available()];
		//读取data.length长度的字节数据,读到data这个Byte数组中存放着
		in.read(data);
		
		//打开字节流,因为我们要通过二进制流下载文件
		ServletOutputStream outputStream = res.getOutputStream();
		outputStream.write(data);
		outputStream.flush(); //清空缓冲区
        //关闭流
		outputStream.close();
		in.close();

3、优化(工具类)

public class FileUtil {
	
	/**
	 * 文件上传功能
	 * @param request
	 * @param path
	 * @return 多文件上传的文件名
	 * @throws Exception
	 */
	public static List<String> uploadFile(HttpServletRequest request,String path) throws Exception{
		Collection<Part> parts = request.getParts();
		List<String> fileNameList = new ArrayList<String>();
		for (Part p : parts) {
			if(p!=null){
				String fileName = p.getSubmittedFileName();
				p.write(path+fileName);
				fileNameList.add(fileName);
			}
		}
		return fileNameList ;
	}
	
	
	/**
	 * 文件下载
	 * @param response
	 * @param pathName
	 * @throws Exception
	 */
	public static void downloadFile(HttpServletResponse response,String pathName) throws Exception{
		File file = new File(pathName);
		if (!file.exists()) {
			System.out.println("文件不存在");
			response.getWriter().write("文件不存在");
			return ;
		}
		
		System.out.println();
		
		response.setContentType("application/octet-stream");
		response.addHeader("Content-Disposition","attachment;filename=" + new String(file.getName().getBytes("utf-8"), "iso-8859-1"));
		response.addHeader("Content-Length", file.length() + "");
		FileInputStream in = new FileInputStream(file);
		byte[] data = new byte[1024*100];
		int i= 0 ;
		ServletOutputStream outputStream = response.getOutputStream();
		while((i=in.read(data)) != -1){
			outputStream.write(data,0,i);
		}
		
		outputStream.flush();  
		outputStream.close();
		in.close();
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值