使用java实现下载文件

本文介绍两种使用Java Web实现附件下载的方法。第一种方法通过直接读取文件并将其转换为字节数组来发送给客户端;第二种方法利用Apache Commons IO库简化文件读取过程。这两种方法均涉及设置HTTP响应头以便浏览器正确处理下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


方法一:
/**
     * 下载附件
     * @param response
     * @throws IOException 
     * @author zhangyd-c
     */
    @RequestMapping(value="/downloadAccessory")
	public void downloadAccessory(String fileName, HttpServletResponse response, HttpServletRequest request) throws IOException
		{
    		request.setCharacterEncoding("utf8");
    		//获取项目真实路径
			String ctxPath = (new StringBuilder(String.valueOf(request.getSession().getServletContext().getRealPath("/")))).append("unstandard_materials/").toString();
			//获取文件的真实路径
			String downLoadPath = (new StringBuilder(String.valueOf(ctxPath))).append(fileName).toString();
			File files = null;
			InputStream fis = null;
			OutputStream os = null;
			try {
				//获取文件
				files = new File(downLoadPath);
				//读取该文件输入流到缓存
				fis = new BufferedInputStream(new FileInputStream(downLoadPath));
				/*
				 * fis.available():返回输入流中估计的字节数(输入流方法的下一次调用的剩余字节数)。
				 */
				byte buffer[] = new byte[fis.available()];
				//按字节读取缓存
				fis.read(buffer);
				response.reset();
				response.addHeader("Content-Disposition", (new StringBuilder("attachment;filename=")).append(new String(fileName.replaceAll(" ", "").getBytes("utf-8"), "iso8859-1")).toString());
				response.addHeader("Content-Length", (new StringBuilder()).append(files.length()).toString());
				os = new BufferedOutputStream(response.getOutputStream());
				response.setContentType("application/octet-stream");
				//将字节数组写入输出流
				os.write(buffer);
				os.flush();
			} catch (FileNotFoundException e) {
				response.setContentType("text/html;charset=UTF-8");
				response.getWriter().write("服务器上不存在该附件(已丢失)!请联系管理员!");
			} catch (IOException e) {
				response.setContentType("text/html;charset=UTF-8");
				response.getWriter().write("服务器异常!请联系管理员!");
			}finally{
				if(fis != null){
					fis.close();
				}
				if(os != null){
					os.close();
				}
			}
		}

 方法二:

/**
     * 下载附件
     * @param response
     * @throws IOException 
     */
    @RequestMapping(value="/downloadAccessory")
	public void downloadAccessory(String fileName, HttpServletResponse response, HttpServletRequest request) throws IOException
		{
    		request.setCharacterEncoding("utf8");
    		response.setContentType("application/octet-stream; charset=utf-8");
    		//获取项目真实路径
			String ctxPath = (new StringBuilder(String.valueOf(request.getSession().getServletContext().getRealPath("/")))).
					append("unstandard_materials/").toString();
			//获取文件的真实路径
			String downLoadPath = (new StringBuilder(String.valueOf(ctxPath))).append(fileName).toString();
			OutputStream out = null;
			 try {
				response.reset();
				 String na = new String(fileName.getBytes("gbk"), "iso8859-1");
				 response.setHeader("Content-Disposition", "attachment; filename="+na);
				 out = response.getOutputStream();
				 out.write(FileUtils.readFileToByteArray(new File(downLoadPath)));
				 out.flush();
			}   catch (IOException e) {
				response.setContentType("text/html;charset=UTF-8");
				response.getWriter().write("服务器异常!请联系管理员!");
			}finally{
				if(out != null){
					out.close();
				}
			}
			
		}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值