Java实现文件下载功能

4,788 阅读1分钟
在SpringMVC的开发过程中,有时需要实现文档的下载功能。文档的下载功能涉及到了java IO流操作的基础知识,下面本文介绍如何使用java来实现后台文档下载功能。

controller

	@ApiOperation("下载")
	@RequestMapping("/download")
	public void downloadFile(HttpServletRequest request,HttpServletResponse response,String filepath) {
		String basePath = request.getSession().getServletContext().getRealPath("/");  
		ServletOutputStream out = null;  
        FileInputStream ips = null;  
        try {
        	// 该url具体看自己的情况来写
			String url = basePath + File.separator + "WEB-INF" + File.separator  + filepath;
			// 获取文件
			File file = new File(url);
			// 获取文件名称
			String filename = file.getName();
			ips = new FileInputStream(file);  

         	 //设置Http响应头告诉浏览器下载这个附件,下载的文件名也是在这里设置的
            response.addHeader("Content-Disposition", "attachment; filename=" + new String(filename.getBytes("UTF-8"),"ISO-8859-1"));
            //设置字符集
            response.setCharacterEncoding("utf-8");
            // form表单则会自动下载
			response.setContentType("multipart/form-data"); 
            out = response.getOutputStream();  
            //读取文件流  
            int len = 0;  
            byte[] buffer = new byte[1024 * 10];  
            while ((len = ips.read(buffer)) != -1){  
                out.write(buffer,0,len);  
            }  
            out.flush();  
		} catch (Exception e){  
            e.printStackTrace();  
        }finally {  
            try {
				out.close();
				ips.close();  
			} catch (IOException e) {
				e.printStackTrace();
			}  
        }  
        
	}

前台

	<form id="form2" action="${request.contextPath}/checkRecord/download" method="get">
			<input id="filepath" name="filepath" type="hidden"/>
	</form>	
	---------------- 以下2行在js文件里面实现 ------------------------------------
	$("#filepath").val(传入文件路径);
	$("#form2").submit(); 表单提交事件

如有错误,欢迎大家指出,会及时修正