现有一些图片在服务器上的链接,在浏览器中打开这些链接是直接显示在浏览器页面的形式。

现在需要生成这些图片的单独下载以及打包下载链接,即在浏览器中打开下载链接后弹出下载框提示下载。由于前端存在跨域问题,所以图片下载由后台接口完成。

首先编写文件下载工具类:

  1. import java.net.URL;
  2. import java.net.MalformedURLException;
  3. import org.apache.commons.io.FileUtils;
  4.  
  5. public class FileDownloadUtil {
  6. /**
  7. * 下载文件---返回下载后的文件存储路径
  8. *
  9. * @param url 文件路径
  10. * @param dir 目标存储目录
  11. * @param fileName 存储文件名
  12. * @return
  13. */
  14. public static void downloadHttpUrl(String url, String dir, String fileName) throws BusinessException {
  15. try {
  16. URL httpurl = new URL(url);
  17. File dirfile = new File(dir);
  18. if (!dirfile.exists()) {
  19. dirfile.mkdirs();
  20. }
  21. FileUtils.copyURLToFile(httpurl, new File(dir+fileName));
  22. } catch (MalformedURLException e) {
  23. e.printStackTrace();
  24. } catch (IOException e) {
  25. e.printStackTrace();26 }
  26. }
  27.  
  28. public static boolean deleteFile(File file) {
  29. if (file.exists()) {
  30. return file.delete();
  31. }
  32. return false;
  33. }

单张图片下载

Controller层接口:

  1. import org.apache.commons.lang.StringUtils;
  2. import java.io.*;
  3.  
  4. protected HttpServletResponse response;
  5.  
  6. /**
  7. * 单张图片下载
  8. *
  9. * @param url 要下载的图片url
  10. * @author: nemowang
  11. */
  12. @ApiImplicitParams({
  13. @ApiImplicitParam(name = "url", value = "图片url", required = true, dataType = "String", paramType = "query"),
  14. })
  15. @ApiOperation(value = "单张图片下载", notes = "单张图片下载")
  16. @RequestMapping(value = "/downloadPicture", method = RequestMethod.GET)
  17. public void downloadPicture(String url) {
  18.  
  19. // 拼接完整图片路径。这里填写图片链接
  20. String urlPath = "";
  21.  
  22. // 获取图片文件后缀名
  23. String postfix = "." + StringUtils.substringAfterLast(url, ".");
  24.  
  25. // 获取当前类的所在项目路径
  26. File directory = new File("");
  27. String courseFile;
  28.  
  29. String srcPath;
  30. File srcFile = null;
  31. FileInputStream fileInputStream = null;
  32. InputStream fis = null;
  33. OutputStream out = null;
  34. try {
  35. courseFile = directory.getCanonicalPath();
  36. String fileName = "\\" + StringUtil.getUUID() + postfix;
  37. // 下载文件
  38. FileDownloadUtil.downloadHttpUrl(urlPath, courseFile, fileName);
  39.  
  40. srcPath = courseFile + fileName;
  41. srcFile = new File(srcPath);
  42.  
  43. fileInputStream = new FileInputStream(srcPath);
  44. fis = new BufferedInputStream(fileInputStream);
  45. byte[] buffer = new byte[fis.available()];
  46. fis.read(buffer);
  47.  
  48. response.setContentType("application/octet-stream");
  49. response.setHeader("Content-disposition", "attachment;filename=" + fileName);
  50. out = response.getOutputStream();
  51. out.write(buffer);
  52. out.flush();
  53. out.close();
  54. } catch (Exception e) {
  55. e.printStackTrace();
  56. } finally {
  57. try {
  58. if (fileInputStream != null) {
  59. fileInputStream.close();
  60. }
  61. if (fis != null) {
  62. fis.close();
  63. }
  64. if (out != null) {
  65. out.close();
  66. }
  67. } catch (IOException e) {
  68. e.printStackTrace();
  69. }
  70. }
  71.  
  72. // 删除中间文件
  73. if (srcFile != null) {
  74. System.out.println(FileDownloadUtil.deleteFile(srcFile));
  75. }
  76. }

因为是GET请求,所以直接拼接接口路由+参数,用浏览器打开就能弹出下载。

至此单张图片下载接口结束。

多张图片打包下载

Controller层接口:

  1. /**
  2. * 图片打包下载
  3. */
  4. @ApiImplicitParams({
  5. @ApiImplicitParam(name = "urls", value = "图片url列表", required = true, dataType = "List", paramType = "query"),
  6. })
  7. @ApiOperation(value = "图片打包下载", notes = "图片打包下载")
  8. @RequestMapping(value = "/downloadPictureList", method = RequestMethod.GET)
  9. public void downloadPictureList(List urls) {
  10. List<String> fileNameList = new ArrayList<>();
  11.  
  12. for (int i = 0; i < urls.size(); i++) {
  13. // 获取文件名
  14. fileNameList.add(StringUtils.substringAfterLast(urls.get(i), "/"));
  15.  
  16. // 拼接完整图片路径
  17. urls.set(i, DOMAIN + urls.get(i));
  18. }
  19.  
  20. // 获取当前类的所在项目路径
  21. File directory = new File("");
  22. String courseFile;
  23.  
  24. String srcPath;
  25. File srcFile = null;
  26.  
  27. // 要打包的文件列表
  28. List<File> fileList = new ArrayList<>();
  29.  
  30. ZipOutputStream zos = null;
  31. OutputStream out = null;
  32. try {
  33. courseFile = directory.getCanonicalPath();
  34.  
  35. // 下载文件
  36. for (int i = 0; i < urls.size(); i++) {
  37. String fileName = "\\" + fileNameList.get(i);
  38. FileDownloadUtil.downloadHttpUrl(urls.get(i), courseFile, fileName);
  39. srcPath = courseFile + fileName;
  40. srcFile = new File(srcPath);
  41. fileList.add(srcFile);
  42. }
  43.  
  44. long start = System.currentTimeMillis();
  45.  
  46. response.setContentType("application/x-zip-compressed");
  47. response.setHeader("Content-disposition", "attachment;filename=" + StringUtil.getUUID() + ".zip");
  48. out = response.getOutputStream();
  49. zos = new ZipOutputStream(out);
  50. for (File file : fileList) {
  51. byte[] buf = new byte[BUFFER_SIZE];
  52. zos.putNextEntry(new ZipEntry(file.getName()));
  53. int len;
  54. FileInputStream in = new FileInputStream(file);
  55. while ((len = in.read(buf)) != -1) {
  56. zos.write(buf, 0, len);
  57. }
  58. zos.closeEntry();
  59. in.close();
  60. }
  61. long end = System.currentTimeMillis();
  62. System.out.println("压缩完成,耗时:" + (end - start) + " ms");
  63.  
  64. out.flush();
  65. } catch (IOException e) {
  66. e.printStackTrace();
  67. } catch (Exception e) {
  68. throw new RuntimeException("zip error from ZipUtils", e);
  69. } finally {
  70. if (zos != null) {
  71. try {
  72. zos.close();
  73. } catch (IOException e) {
  74. e.printStackTrace();
  75. }
  76. }
  77. if (out != null) {
  78. try {
  79. zos.close();
  80. } catch (IOException e) {
  81. e.printStackTrace();
  82. }
  83. }
  84. }
  85.  
  86. // 删除中间文件
  87. if (fileList != null) {
  88. for (File file : fileList) {
  89. System.out.println(FileDownloadUtil.deleteFile(file));
  90. }
  91. }
  92. }

同样是GET请求,所以也是拼接接口路由+参数,用浏览器打开就能弹出下载。

Java Springboot 根据图片链接生成图片下载链接 及 多个图片打包zip下载链接的更多相关文章

  1. 打包zip下载

    //首先引入的文件为org.apache的切记不是jdk的import org.apache.tools.zip.ZipOutputStream;import org.apache.tools.zip ...

  2. 批量下载,多文件压缩打包zip下载

    0.写在前面的话 图片批量下载,要求下载时集成为一个压缩包进行下载.从昨天下午折腾到现在,踩坑踩得莫名其妙,还是来唠唠,给自己留个印象的同时,也希望给需要用到这个方法的人带来一些帮助. 1.先叨叨IO ...

  3. Web端文件打包.zip下载

    使用ant.jar包的API进行文件夹打包.直接上代码: String zipfilename = "test.zip"; File zipfile = new File(zipf ...

  4. 文件打包,下载之使用PHP自带的ZipArchive压缩文件并下载打包好的文件

    总结:                                                          使用PHP下载文件的操作需要给出四个header(),可以参考我的另一篇博文: ...

  5. 轻量级JAVA+EE企业应用实战(第4版)pdf电子书和源码的免费下载链接

    轻量级JAVA+EE企业应用实战(第4版)pdf电子书和源码的免费下载链接: pdf链接:https://pan.baidu.com/s/1dYIWtsv2haL4v7vx3w-8WQ 无提取密码源码 ...

  6. java后台中处理图片辅助类汇总(上传图片到服务器,从服务器下载图片保存到本地,缩放图片,copy图片,往图片添加水印图片或者文字,生成二维码,删除图片等)

    最近工作中处理小程序宝箱活动,需要java画海报,所以把这块都快百度遍了,记录一下处理的方法,百度博客上面也有不少坑! 获取本地图片路径: String bgPath = Thread.current ...

  7. Java爬虫之下载全世界国家的国旗图片

    介绍   本篇博客将继续上一篇博客:Python爬虫之使用Fiddler+Postman+Python的requests模块爬取各国国旗 的内容,将用Java来实现这个爬虫,下载全世界国家的国旗图片. ...

  8. JAVA根据URL生成二维码图片、根据路径生成二维码图片

    引入jar包 zxing-2.3.0.jar.IKAnalyzer2012_u6.jar 下载地址:https://yvioo.lanzous.com/b00nlbp6h                ...

  9. java springboot调用第三方接口 借助hutoool工具类 爬坑

    楼主是个后端小白一枚,之前没接触过后端,只学了java基本语法,还是在学校老师教的,学的很浅,什么ssh.ssm框架都没有学,最近在自学spring boot,看书学也看不是很懂,就在b站上看教学视频 ...

随机推荐

  1. mysql 8.0.16 单主 mgr搭建

    mysql 8.0.16 单主 mgr搭建 环境介绍: 192.168.142.142 db142192.168.142.143 db143192.168.142.145 db145 1.安装依赖包 ...

  2. ftp CentOS7安装

    1.安装ftp服务yum install vsftpd 2.修改ftp配置文件(/etc/vsftpd/vsftpd.conf)ascii_upload_enable=YESascii_downloa ...

  3. electron打包成.exe后限制只启动一个应用

    注意:这是2.x的文档 const {app} = require('electron') let myWindow = null const shouldQuit = app.makeSingleI ...

  4. Vue的watch和computed方法的使用

    Vue的watch属性 Vue的watch属性可以用来监听data属性中数据的变化 <!DOCTYPE html> <html> <head> <meta c ...

  5. ubuntu1604-Python35-cuda9-cudnn7-gpu-dockerfile

    一,在某目录下有如下文件: -rw-r--r-- 1 root root 1643293725 9月 2 11:46 cuda_9.0.176_384.81_linux.run -rw-r--r-- ...

  6. 谁掳走了 nginx.pid 文件?

    1.重载配置 执行 nginx  -s   reload  命令,报错:找不到 nginx.pid 文件,无法打开.曾经屡试不爽的命令,此时,竟然失灵了? 刚开始,我一头雾水,有点丈二和尚摸不着头脑… ...

  7. Linux 查看内存(free)、释放内存(基本操作)

    原文链接:http://blog.51cto.com/11495268/2384147 1.简介 1.1 介绍 很多时候,服务器 负载 很高(执行操作 很慢),很多 原因 造成 这种 现象(内存不足 ...

  8. 苹果cms开启防红跳转后,提示模板文件不存在解决方法

    1,苹果cms开启防红跳转后,提示模板文件不存在(如下图)这是因为你使用的模板里面缺少苹果cms自带的防红跳转模板导致,遇到这种状况后需要把苹果cms默认自带的( template/default_p ...

  9. spring cloud:hystrix-dashboard-turbine

    hystrix-dashboard-turbine-server 1. File-->new spring starter project 2.add dependency <parent ...

  10. 为什么电脑连接不上FTP

    我们对服务器的FTP状况有实时监控,一般问题都不在服务器端. 而且我们客服一般会第一时间测试下您空间FTP是否真的不能连接 99%绝大部分FTP连接不上的问题,都是客户那边的软件端或网络问题. 问题分 ...