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站上看教学视频 ...
随机推荐
- MongoDB 副本集+分片 认证方式搭建
MongoDB 副本集+分片 认证方式搭建 参考资料: https://www.cnblogs.com/ityouknow/p/7344005.htmlhttps://jorwen-fang.itey ...
- springboot+mybatis日志显示SQL的最简单方法
在springBoot+Mybatis日志显示SQL的执行情况的最简单方法就是在properties新增:logging.level.cn.piesat.mapper=debug 注意:其中cn.pi ...
- Type.GetType反射的对象创建Activator.CreateInstance
/// <summary> /// 获取对应类的实现 /// </summary> /// <param name="libname">< ...
- print和赋值
赋值 #可同时(并行)给多个变量赋值 x, y, z = 1, 2, 3 #交换多个变量的值 x, y = y, x 序列解包(或可迭代对象解包):将一个序列(或任何可迭代对象)解包,并将得到的值存储 ...
- jquery empty选择器 语法
jquery empty选择器 语法 作用::empty 选择器选取空的元素.空元素指的是不包含子元素或文本的元素.直线电机滑台 语法:$(":empty") jquery emp ...
- python 线程模块
Python通过两个标准库thread和threading提供对线程的支持.thread提供了低级别的.原始的线程以及一个简单的锁. threading 模块提供的其他方法: threading.cu ...
- Selenium 三种等待方式详解
我们在做WEB自动化时,一般要等待页面元素加载完成后,才能执行操作,否则会报找不到元素的错误,这样就要求我们在有些场景下加等待时间. 我们平常用到的有三种等待方式: 强制等待 隐式等待 显示等待 一. ...
- java web程序上传文件,浏览器显示连接被重置
上传文件时,到13%时浏览器显示连接被重置如图: 参考网上很多方法 比如设置server.xml 的相应大小.时间,然并没有解决问题 connectionTimeout="2000000&q ...
- 取值函数(getter)和存值函数(setter)
todo get和set关键字
- maven 高级玩法
maven 高级玩法 标签(空格分隔): maven 实用技巧 Maven 提速 多线程 # 用 4 个线程构建,以及根据 CPU 核数每个核分配 1 个线程进行构建 $ mvn -T 4 clean ...