java web实现文件下载

 

        /** 下载视频 */
	@Scope(value="prototype")
	@RequestMapping(value = "/filedownload.do")
	public void fileDownload(String videoSrc,HttpServletRequest req, HttpServletResponse resp) throws IOException {
			ServletOutputStream out = null;
			FileInputStream in = null;
			ByteArrayOutputStream bos = null;
			ByteArrayInputStream ios = null;
			try {
				req.setCharacterEncoding("UTF-8");
				resp.setCharacterEncoding("UTF-8");
				String videoRealPath = req.getRealPath(videoSrc);
				String fileType = videoRealPath.substring(videoRealPath.lastIndexOf("."));
				String videoName = "测试";
				String fileName = URLDecoder.decode(videoName, "utf-8") + fileType;
				File file = new File(videoRealPath);
				in = new FileInputStream(file);
				bos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int n;
				while ((n = in.read(buffer)) != -1) {
					bos.write(buffer, 0, n);
				}
				byte[] bytes = bos.toByteArray();
				ios = new ByteArrayInputStream(bytes);
				String _fileName = URLEncoder.encode(fileName, "UTF-8");
				if (fileName.length() > 150) {
					String guessCharset = "UTF-8"; 
					_fileName = new String(fileName.getBytes(guessCharset),"ISO8859-1");
				}
				resp.setHeader("Content-Disposition", "attachment;filename="+ _fileName.replace("+", "%20").replaceAll("%28", "(").replaceAll("%29", ")"));
				byte[] buff = new byte[1024];
				out = resp.getOutputStream();
				int leng = ios.read(buff);
				while (leng > 0) {
					out.write(buff, 0, leng);
					leng = ios.read(buff);
				}
				
			} catch (Exception ex) {
				ex.printStackTrace();
			} finally {
				if (out != null) {
					try {
						out.flush();
					} catch (IOException e) {
						e.printStackTrace();
					}
					try {
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (in != null) {
					try {
						in.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
	}

推荐一个公众号

号主为一线大厂架构师,CSDN博客专家,博客访问量突破一千万。主要分享Java、golang架构,源码,分布式,高并发等技术,用大厂程序员的视角来探讨技术进阶、面试指南、职业规划等。15W技术人的选择!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张音乐

请我喝杯咖啡吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值