首页 > 其他分享 >springboot文件流下载

springboot文件流下载

时间:2022-11-08 13:55:40浏览次数:60  
标签:文件 springboot param filename path new response 下载

1. 将文件以流的形式一次性读取到内存,通过响应输出流输出到前端

  1. /**
  2. * @param path 想要下载的文件的路径
  3. * @param response
  4. * @功能描述 下载文件:
  5. */
  6. @RequestMapping("/download")
  7. public void download(String path, HttpServletResponse response) {
  8. try {
  9. // path是指想要下载的文件的路径
  10. File file = new File(path);
  11. log.info(file.getPath());
  12. // 获取文件名
  13. String filename = file.getName();
  14. // 获取文件后缀名
  15. String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
  16. log.info("文件后缀名:" + ext);
  17. // 将文件写入输入流
  18. FileInputStream fileInputStream = new FileInputStream(file);
  19. InputStream fis = new BufferedInputStream(fileInputStream);
  20. byte[] buffer = new byte[fis.available()];
  21. fis.read(buffer);
  22. fis.close();
  23. // 清空response
  24. response.reset();
  25. // 设置response的Header
  26. response.setCharacterEncoding("UTF-8");
  27. //Content-Disposition的作用:告知浏览器以何种方式显示响应返回的文件,用浏览器打开还是以附件的形式下载到本地保存
  28. //attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
  29. // filename表示文件的默认名称,因为网络传输只支持URL编码的相关支付,因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
  30. response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
  31. // 告知浏览器文件的大小
  32. response.addHeader("Content-Length", "" + file.length());
  33. OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
  34. response.setContentType("application/octet-stream");
  35. outputStream.write(buffer);
  36. outputStream.flush();
  37. } catch (IOException ex) {
  38. ex.printStackTrace();
  39. }


2. 将输入流中的数据循环写入到响应输出流中,而不是一次性读取到内存,通过响应输出流输出到前端

  1. /**
  2. * @param path 指想要下载的文件的路径
  3. * @param response
  4. * @功能描述 下载文件:将输入流中的数据循环写入到响应输出流中,而不是一次性读取到内存
  5. */
  6. @RequestMapping("/downloadLocal")
  7. public void downloadLocal(String path, HttpServletResponse response) throws IOException {
  8. // 读到流中
  9. InputStream inputStream = new FileInputStream(path);// 文件的存放路径
  10. response.reset();
  11. response.setContentType("application/octet-stream");
  12. String filename = new File(path).getName();
  13. response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
  14. ServletOutputStream outputStream = response.getOutputStream();
  15. byte[] b = new byte[1024];
  16. int len;
  17. //从输入流中读取一定数量的字节,并将其存储在缓冲区字节数组中,读到末尾返回-1
  18. while ((len = inputStream.read(b)) > 0) {
  19. outputStream.write(b, 0, len);
  20. }
  21. inputStream.close();


3. 下载网络文件到本地

  1. /**
  2. * @param path 下载后的文件路径和名称
  3. * @param netAddress 文件所在网络地址
  4. * @功能描述 网络文件下载到服务器本地
  5. */
  6. @RequestMapping("/netDownloadLocal")
  7. public void downloadNet(String netAddress, String path) throws IOException {
  8. URL url = new URL(netAddress);
  9. URLConnection conn = url.openConnection();
  10. InputStream inputStream = conn.getInputStream();
  11. FileOutputStream fileOutputStream = new FileOutputStream(path);
  12. int bytesum = 0;
  13. int byteread;
  14. byte[] buffer = new byte[1024];
  15. while ((byteread = inputStream.read(buffer)) != -1) {
  16. bytesum += byteread;
  17. System.out.println(bytesum);
  18. fileOutputStream.write(buffer, 0, byteread);
  19. }
  20. fileOutputStream.close();


4. 网络文件获取到服务器后,经服务器处理后响应给前端

  1. /**
  2. * @param netAddress
  3. * @param filename
  4. * @param isOnLine
  5. * @param response
  6. * @功能描述 网络文件获取到服务器后,经服务器处理后响应给前端
  7. */
  8. @RequestMapping("/netDownLoadNet")
  9. public void netDownLoadNet(String netAddress, String filename, boolean isOnLine, HttpServletResponse response) throws Exception {
  10. URL url = new URL(netAddress);
  11. URLConnection conn = url.openConnection();
  12. InputStream inputStream = conn.getInputStream();
  13. response.reset();
  14. response.setContentType(conn.getContentType());
  15. if (isOnLine) {
  16. // 在线打开方式 文件名应该编码成UTF-8
  17. response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(filename, "UTF-8"));
  18. } else {
  19. //纯下载方式 文件名应该编码成UTF-8
  20. response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
  21. }
  22. byte[] buffer = new byte[1024];
  23. int len;
  24. OutputStream outputStream = response.getOutputStream();
  25. while ((len = inputStream.read(buffer)) > 0) {
  26. outputStream.write(buffer, 0, len);
  27. }
  28. inputStream.close();

标签:文件,springboot,param,filename,path,new,response,下载
From: https://www.cnblogs.com/DeveloperPan/p/SpringBootFileDownload.html

相关文章

  • vs2022 git上看不到已更改文件
    VisualStudio2022显示“解析git状态输出时出错。”。这可能是因为git或VisualStudio的版本不匹配。作为一种解决方法,您可以在“包管理器控制台”中运行以下命令......
  • Java文件的创建、删除
    1.如何创建文件?  创建文件对象相关构造器newFile(Stringpathname)//根据路径构造一个File对象newFile(Fileparent,Stringchild)//根据父目录文件+子路径构建......
  • 文件的操作!!!
    关于文件创建的三种方式。importorg.testng.annotations.Test;importsun.awt.geom.AreaOp;importjava.io.File;importjava.io.IOException;publicclasshhh{publ......
  • 用Java方法创建、查看文件目录
    一、创建、查看文件  首先插入包java.io.*,然后创建File对象。   有三种方法创建文件,不过都是将创建文件的绝对路径用String类型数据保存,在创建File对象时引用St......
  • 下载Redis并设置自启动
    Redis的下载地址:https://github.com/MicrosoftArchive/redis/releases/tag/win-3.2.100进入解压后的文件夹,输入命令 redis-serverredis.windows.conf后回车,如下即表示......
  • git代码管理 之 文件夹/文件修改大小写问题
    问题复现1、创建一个TEST文件夹,TEST文件夹下有一个test.js文件。2、将这个修改推送到gitee仓库上3、修改本地文件夹的名字大小写,从TEST,修改为Test。这个时候就出现......
  • SpringBoot构建war部署到tomcat中无法注册到Nacos服务
    最近项目基本开发完成,准备部署到服务器中进行功能的验证,但当把所有的环境都搭建好,启动项目后,tomcat启动日志正常,发现在服务调用时一直报错。项目是使用SpringBoot框架搭建......
  • HTML5 WEB怎么实现大文件上传
    ​ 需求:项目要支持大文件上传功能,经过讨论,初步将文件上传大小控制在500G内,因此自己需要在项目中进行文件上传部分的调整和配置,自己将大小都以500G来进行限制。PC端全平......
  • android 删除文件错误:open failed: EBUSY (Device or resource busy)
    引用:​​http://stackoverflow.com/questions/11539657/open-failed-ebusy-device-or-resource-busy​​IhavethebigAnswer!!TheProblemcomesfromtheAndroidSys......
  • 处理时间转换不正确-Springboot、springclound、feign、http请求
    SpringBoot、SpringCloud、feign、前后端时间解析不正确时,我们可以自定义HttpMessageConverters,以达到我们希望的结果参考链接:https://www.cnblogs.com/nhdlb/p/12783624.......