获取七牛图片URL,使用流来下载图片
一、工具类
package com.bayan.keke.util;
import net.sf.json.JSONObject;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @param sourceUrls :待压缩的文件路径(Map:key="imgName",key="imgUrl")
* @param zos :压缩后的输出流
* *@param fileName :压缩后文件的名称
* @return
* */
public static boolean downloadToZip(List<Map<String,String>> sourceUrls,ZipOutputStream zos){
boolean flag = false;
//输入
InputStream fis = null;
BufferedInputStream bis = null;
try {
// 10K的数据缓冲
byte[] bufs = new byte[1024*10];
for(Map<String,String> sourceUrl : sourceUrls){
//fileName
//String imgName= DateUtil.getStringByFormat(System.currentTimeMillis(),DateUtil.dateFormatYMDHMS);
String imgName = sourceUrl.get("imgName");
// 构造URL
URL url = new URL(sourceUrl.get("imgUrl"));
// 打开连接
URLConnection con = url.openConnection();
//设置请求超时为5s
con.setConnectTimeout(5 * 1000);
//读取待压缩的文件并写进压缩包里
fis = con.getInputStream();
bis = new BufferedInputStream(fis, 1024*10);
//创建ZIP实体,并添加进压缩包
ZipEntry zipEntry = new ZipEntry(imgName +".jpg");
zos.putNextEntry(zipEntry);
int read = 0;
while((read=bis.read(bufs, 0, 1024*10)) != -1){
zos.write(bufs,0,read);
}
}
flag = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
System.out.println("连接中断!");
e.printStackTrace();
}finally {
//关闭流
try {
if(null != bis) bis.close();
if(null != zos) zos.close();
if(null != fis) fis.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
return flag;
}
}
二、action
public void downTasksToZip(){
int taskResult = 0;
try {
String param = getRequest().getParameter("result");
if( param != null ){
taskResult = Integer.parseInt(param);
}
// 设置响应头,控制浏览器下载该文件
getResponse().setHeader("content-disposition","attachment;filename=" + URLEncoder.encode("图片.zip", "UTF-8"));
// 创建输出流
OutputStream outputStream = getResponse().getOutputStream();
ZipOutputStream zos = new ZipOutputStream(outputStream);
//获取所有图片url
List<Map<String,String>> list = imageService.getImageUrl(taskResult);
if( list.size() > 0){
boolean rst = DownLoadUtil.downloadToZip(list,zos);
}
// 请求结束log
outputStream.close();
} catch (Exception e) {
printSysErr(e, logger);
}
}
三、拼接图片url
使用时间戳防盗链,这里不再细说,具体可参考上一篇博客
/**
*获取所有被推荐作业的url
*/
public List<Map<String,String>> getImageUrl(Integer type)throws Exception{
List<Map<String,String>> list = new ArrayList<>();
List<String > photoUrls = iamgeDao.getImageUrl(type);
for(String s: photoUrls){
Map map = new HashMap();
String[] strings = s.split("/");
map.put("imgName",strings[strings.length -1]);
map.put("imgUrl",Common.getUrlSign(s));
list.add(map);
}
return list;
}