Java Springboot 根据图片链接生成图片下载链接 及 多个图片打包zip下载链接
现有一些图片在服务器上的链接,在浏览器中打开这些链接是直接显示在浏览器页面的形式。
现在需要生成这些图片的单独下载以及打包下载链接,即在浏览器中打开下载链接后弹出下载框提示下载。由于前端存在跨域问题,所以图片下载由后台接口完成。
首先编写文件下载工具类:
- import java.net.URL;
- import java.net.MalformedURLException;
- import org.apache.commons.io.FileUtils;
- public class FileDownloadUtil {
- /**
- * 下载文件---返回下载后的文件存储路径
- *
- * @param url 文件路径
- * @param dir 目标存储目录
- * @param fileName 存储文件名
- * @return
- */
- public static void downloadHttpUrl(String url, String dir, String fileName) throws BusinessException {
- try {
- URL httpurl = new URL(url);
- File dirfile = new File(dir);
- if (!dirfile.exists()) {
- dirfile.mkdirs();
- }
- FileUtils.copyURLToFile(httpurl, new File(dir+fileName));
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();26 }
- }
- public static boolean deleteFile(File file) {
- if (file.exists()) {
- return file.delete();
- }
- return false;
- }
- }
单张图片下载
Controller层接口:
- import org.apache.commons.lang.StringUtils;
- import java.io.*;
- protected HttpServletResponse response;
- /**
- * 单张图片下载
- *
- * @param url 要下载的图片url
- * @author: nemowang
- */
- @ApiImplicitParams({
- @ApiImplicitParam(name = "url", value = "图片url", required = true, dataType = "String", paramType = "query"),
- })
- @ApiOperation(value = "单张图片下载", notes = "单张图片下载")
- @RequestMapping(value = "/downloadPicture", method = RequestMethod.GET)
- public void downloadPicture(String url) {
- // 拼接完整图片路径。这里填写图片链接
- String urlPath = "";
- // 获取图片文件后缀名
- String postfix = "." + StringUtils.substringAfterLast(url, ".");
- // 获取当前类的所在项目路径
- File directory = new File("");
- String courseFile;
- String srcPath;
- File srcFile = null;
- FileInputStream fileInputStream = null;
- InputStream fis = null;
- OutputStream out = null;
- try {
- courseFile = directory.getCanonicalPath();
- String fileName = "\\" + StringUtil.getUUID() + postfix;
- // 下载文件
- FileDownloadUtil.downloadHttpUrl(urlPath, courseFile, fileName);
- srcPath = courseFile + fileName;
- srcFile = new File(srcPath);
- fileInputStream = new FileInputStream(srcPath);
- fis = new BufferedInputStream(fileInputStream);
- byte[] buffer = new byte[fis.available()];
- fis.read(buffer);
- response.setContentType("application/octet-stream");
- response.setHeader("Content-disposition", "attachment;filename=" + fileName);
- out = response.getOutputStream();
- out.write(buffer);
- out.flush();
- out.close();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- if (fileInputStream != null) {
- fileInputStream.close();
- }
- if (fis != null) {
- fis.close();
- }
- if (out != null) {
- out.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- // 删除中间文件
- if (srcFile != null) {
- System.out.println(FileDownloadUtil.deleteFile(srcFile));
- }
- }
因为是GET请求,所以直接拼接接口路由+参数,用浏览器打开就能弹出下载。
至此单张图片下载接口结束。
多张图片打包下载
Controller层接口:
- /**
- * 图片打包下载
- */
- @ApiImplicitParams({
- @ApiImplicitParam(name = "urls", value = "图片url列表", required = true, dataType = "List", paramType = "query"),
- })
- @ApiOperation(value = "图片打包下载", notes = "图片打包下载")
- @RequestMapping(value = "/downloadPictureList", method = RequestMethod.GET)
- public void downloadPictureList(List urls) {
- List<String> fileNameList = new ArrayList<>();
- for (int i = 0; i < urls.size(); i++) {
- // 获取文件名
- fileNameList.add(StringUtils.substringAfterLast(urls.get(i), "/"));
- // 拼接完整图片路径
- urls.set(i, DOMAIN + urls.get(i));
- }
- // 获取当前类的所在项目路径
- File directory = new File("");
- String courseFile;
- String srcPath;
- File srcFile = null;
- // 要打包的文件列表
- List<File> fileList = new ArrayList<>();
- ZipOutputStream zos = null;
- OutputStream out = null;
- try {
- courseFile = directory.getCanonicalPath();
- // 下载文件
- for (int i = 0; i < urls.size(); i++) {
- String fileName = "\\" + fileNameList.get(i);
- FileDownloadUtil.downloadHttpUrl(urls.get(i), courseFile, fileName);
- srcPath = courseFile + fileName;
- srcFile = new File(srcPath);
- fileList.add(srcFile);
- }
- long start = System.currentTimeMillis();
- response.setContentType("application/x-zip-compressed");
- response.setHeader("Content-disposition", "attachment;filename=" + StringUtil.getUUID() + ".zip");
- out = response.getOutputStream();
- zos = new ZipOutputStream(out);
- for (File file : fileList) {
- byte[] buf = new byte[BUFFER_SIZE];
- zos.putNextEntry(new ZipEntry(file.getName()));
- int len;
- FileInputStream in = new FileInputStream(file);
- while ((len = in.read(buf)) != -1) {
- zos.write(buf, 0, len);
- }
- zos.closeEntry();
- in.close();
- }
- long end = System.currentTimeMillis();
- System.out.println("压缩完成,耗时:" + (end - start) + " ms");
- out.flush();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (Exception e) {
- throw new RuntimeException("zip error from ZipUtils", e);
- } finally {
- if (zos != null) {
- try {
- zos.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (out != null) {
- try {
- zos.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- // 删除中间文件
- if (fileList != null) {
- for (File file : fileList) {
- System.out.println(FileDownloadUtil.deleteFile(file));
- }
- }
- }
同样是GET请求,所以也是拼接接口路由+参数,用浏览器打开就能弹出下载。
Java Springboot 根据图片链接生成图片下载链接 及 多个图片打包zip下载链接的更多相关文章
- 打包zip下载
//首先引入的文件为org.apache的切记不是jdk的import org.apache.tools.zip.ZipOutputStream;import org.apache.tools.zip ...
- 批量下载,多文件压缩打包zip下载
0.写在前面的话 图片批量下载,要求下载时集成为一个压缩包进行下载.从昨天下午折腾到现在,踩坑踩得莫名其妙,还是来唠唠,给自己留个印象的同时,也希望给需要用到这个方法的人带来一些帮助. 1.先叨叨IO ...
- Web端文件打包.zip下载
使用ant.jar包的API进行文件夹打包.直接上代码: String zipfilename = "test.zip"; File zipfile = new File(zipf ...
- 文件打包,下载之使用PHP自带的ZipArchive压缩文件并下载打包好的文件
总结: 使用PHP下载文件的操作需要给出四个header(),可以参考我的另一篇博文: ...
- 轻量级JAVA+EE企业应用实战(第4版)pdf电子书和源码的免费下载链接
轻量级JAVA+EE企业应用实战(第4版)pdf电子书和源码的免费下载链接: pdf链接:https://pan.baidu.com/s/1dYIWtsv2haL4v7vx3w-8WQ 无提取密码源码 ...
- java后台中处理图片辅助类汇总(上传图片到服务器,从服务器下载图片保存到本地,缩放图片,copy图片,往图片添加水印图片或者文字,生成二维码,删除图片等)
最近工作中处理小程序宝箱活动,需要java画海报,所以把这块都快百度遍了,记录一下处理的方法,百度博客上面也有不少坑! 获取本地图片路径: String bgPath = Thread.current ...
- Java爬虫之下载全世界国家的国旗图片
介绍 本篇博客将继续上一篇博客:Python爬虫之使用Fiddler+Postman+Python的requests模块爬取各国国旗 的内容,将用Java来实现这个爬虫,下载全世界国家的国旗图片. ...
- JAVA根据URL生成二维码图片、根据路径生成二维码图片
引入jar包 zxing-2.3.0.jar.IKAnalyzer2012_u6.jar 下载地址:https://yvioo.lanzous.com/b00nlbp6h ...
- java springboot调用第三方接口 借助hutoool工具类 爬坑
楼主是个后端小白一枚,之前没接触过后端,只学了java基本语法,还是在学校老师教的,学的很浅,什么ssh.ssm框架都没有学,最近在自学spring boot,看书学也看不是很懂,就在b站上看教学视频 ...
随机推荐
- mysql 8.0.16 单主 mgr搭建
mysql 8.0.16 单主 mgr搭建 环境介绍: 192.168.142.142 db142192.168.142.143 db143192.168.142.145 db145 1.安装依赖包 ...
- ftp CentOS7安装
1.安装ftp服务yum install vsftpd 2.修改ftp配置文件(/etc/vsftpd/vsftpd.conf)ascii_upload_enable=YESascii_downloa ...
- electron打包成.exe后限制只启动一个应用
注意:这是2.x的文档 const {app} = require('electron') let myWindow = null const shouldQuit = app.makeSingleI ...
- Vue的watch和computed方法的使用
Vue的watch属性 Vue的watch属性可以用来监听data属性中数据的变化 <!DOCTYPE html> <html> <head> <meta c ...
- 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-- ...
- 谁掳走了 nginx.pid 文件?
1.重载配置 执行 nginx -s reload 命令,报错:找不到 nginx.pid 文件,无法打开.曾经屡试不爽的命令,此时,竟然失灵了? 刚开始,我一头雾水,有点丈二和尚摸不着头脑… ...
- Linux 查看内存(free)、释放内存(基本操作)
原文链接:http://blog.51cto.com/11495268/2384147 1.简介 1.1 介绍 很多时候,服务器 负载 很高(执行操作 很慢),很多 原因 造成 这种 现象(内存不足 ...
- 苹果cms开启防红跳转后,提示模板文件不存在解决方法
1,苹果cms开启防红跳转后,提示模板文件不存在(如下图)这是因为你使用的模板里面缺少苹果cms自带的防红跳转模板导致,遇到这种状况后需要把苹果cms默认自带的( template/default_p ...
- spring cloud:hystrix-dashboard-turbine
hystrix-dashboard-turbine-server 1. File-->new spring starter project 2.add dependency <parent ...
- 为什么电脑连接不上FTP
我们对服务器的FTP状况有实时监控,一般问题都不在服务器端. 而且我们客服一般会第一时间测试下您空间FTP是否真的不能连接 99%绝大部分FTP连接不上的问题,都是客户那边的软件端或网络问题. 问题分 ...