直接上代码,接口如下:
@GetMapping("/testDowload")
public R> dowloaImageGraceFully(@RequestParam("orderId") String orderId) {
//本地路径 存储下载图片的路径
String storePath = "C:/Users/Public/Pictures/img";
List listStr = new ArrayList<>();
//获取图片路径 从文件服务器中
//根据订单号 从数据库中 查询 图片的id
List list = orderMapper.downloadHtById(orderId);
if (list == null){
return R.ok("合同还未上传,请联系管理员!");
}else {
for (int i = 0; i < list.size(); i++) {
String managementrightContract = list.get(i).getManagementrightContract();
//id可能有多个,所以在这里进行分开查询
String [] arr = managementrightContract.split(",");
if (arr.length>0){
//根据id 从文件服务器中获取到相应的图片存储路径
for (int j = 0; j < arr.length; j++) {
IaFileStore iaFileStore = iaFileStoreMapper.selectOne(new QueryWrapper().eq("id", arr[j]));
if (null ==iaFileStore){
return R.ok("下载失败!");
}else {
IaFiles iaFiles = fileService.getOne(new QueryWrapper().eq("file_name",iaFileStore.getName()));
//将获取出来的图片路径存放到list中
listStr.add(fileService.getFileUrl(iaFiles.getUuid()));
//也可以将以下方法放在这里,就可以减少使用list转换,在这里我就不改了
}
}
}
}
}
//将list中的的数据拿出来转换为 字符串 (这里也可以放再上面.不用存储到list中)
for (int i = 0; i < listStr.size(); i++) {
String a1 = listStr.get(i);
System.out.println(a1);
String filename = snowflakeIdWorker.nextId() + "";
//调用下载图片工具类,进行下载 循环下载图片
DowloadUtil.dowloaImage(a1,filename,storePath);
}
return R.ok("文件下载成功!");
}
工具类
package com.ruoyi.business.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class DowloadUtil {
public static void dowloaImage(String imageUrl, String formatName, String storePath) {
InputStream is = null;
FileOutputStream fos = null;
File storeDir = new File(storePath);
if (!storeDir.exists()) {
storeDir.mkdirs();
}
String[] str = imageUrl.substring(imageUrl.lastIndexOf("/") + 1).split("\.");
String suffix = null;
if (str.length == 1) {
suffix = "jpg";
} else {
suffix = str[1];
}
String filename = formatName + "." + suffix;
try {
URL url = new URL(imageUrl);
URLConnection con = url.openConnection();
is = con.getInputStream();
fos = new FileOutputStream(new File(storeDir, filename));
byte[] buff = new byte[1024];
int len = 0;
while ((len = is.read(buff)) != -1) {
fos.write(buff, 0, len);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
下载结果: