之前遇到需要将一个url视频地址的视频和一段数据库查询的介绍文字生成txt文档,一起压缩并下载的需求,
然后找了很久的资料,最后同事分享给我的。现在想起来就记录一下,挺实用的。
两个类,一个util类,一个controll类
---------------------------------------------------class1----------------------------------------------------
package cn.hfbin.seckill.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @Author: lx
* @Description:
* @Date: 2020/12/17 16:28
*/
public class UrlFilesToZip {
private static final Logger logger = LoggerFactory.getLogger(UrlFilesToZip.class);
//根据文件链接把文件下载下来并且转成字节码
public byte[] getImageFromURL(String urlPath) {
byte[] data = null;
InputStream is = null;
HttpURLConnection conn = null;
try {
URL url = new URL(urlPath);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
// conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setConnectTimeout(6000);
is = conn.getInputStream();
if (conn.getResponseCode() == 200) {
data = readInputStream(is);
} else {
data = null;
}
} catch (MalformedURLException e) {
logger.error("MalformedURLException", e);
} catch (IOException e) {
logger.error("IOException", e);
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
logger.error("IOException", e);
}
conn.disconnect();
}
return data;
}
public byte[] readInputStream(InputStream is) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = -1;
try {
while ((length = is.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
baos.flush();
} catch (IOException e) {
logger.error("IOException", e);
}
byte[] data = baos.toByteArray();
try {
is.close();
baos.close();
} catch (IOException e) {
logger.error("IOException", e);
}
return data;
}
}
---------------------------------------------------class2----------------------------------------------------
package cn.hfbin.seckill.controller;
import cn.hfbin.seckill.bo.GoodsBo;
import cn.hfbin.seckill.config.UrlFilesToZip;
import cn.hfbin.seckill.entity.OrderInfo;
import cn.hfbin.seckill.entity.User;
import cn.hfbin.seckill.redis.RedisService;
import cn.hfbin.seckill.redis.UserKey;
import cn.hfbin.seckill.result.CodeMsg;
import cn.hfbin.seckill.result.Result;
import cn.hfbin.seckill.service.SeckillGoodsService;
import cn.hfbin.seckill.service.SeckillOrderService;
import cn.hfbin.seckill.util.CookieUtil;
import cn.hfbin.seckill.vo.OrderDetailVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* Created by: HuangFuBin
* Date: 2018/7/19
* Time: 0:56
* Such description:
*/
@Controller
@RequestMapping("/order")
@Slf4j
public class SeckillOrderController {
@Autowired
RedisService redisService;
@Autowired
SeckillOrderService seckillOrderService;
@Autowired
SeckillGoodsService seckillGoodsService;
@RequestMapping("/detail")
@ResponseBody
public Result<OrderDetailVo> info(Model model,
@RequestParam("orderId") long orderId , HttpServletRequest request) {
String loginToken = CookieUtil.readLoginToken(request);
User user = redisService.get(UserKey.getByName, loginToken, User.class);
if(user == null) {
return Result.error(CodeMsg.USER_NO_LOGIN);
}
OrderInfo order = seckillOrderService.getOrderInfo(orderId);
if(order == null) {
return Result.error(CodeMsg.ORDER_NOT_EXIST);
}
long goodsId = order.getGoodsId();
GoodsBo goods = seckillGoodsService.getseckillGoodsBoByGoodsId(goodsId);
OrderDetailVo vo = new OrderDetailVo();
vo.setOrder(order);
vo.setGoods(goods);
return Result.success(vo);
}
@RequestMapping("/file")
public void zipFile(HttpServletResponse response){
try {
String[] urls = {"https://c-cms-v-a-test.oss-cn-beijing.aliyuncs.com/video/3002/p/496d04bc9fc5bf3f799ba1b3e7c1c3d3-4da02575440e426b9194281c21db5c07-2.mp4"};
String filename = new String("xx.zip".getBytes("UTF-8"), "ISO8859-1");//控制文件名编码
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(bos);
UrlFilesToZip s = new UrlFilesToZip();
int idx = 1;
for (String oneFile : urls) {
zos.putNextEntry(new ZipEntry("profile" + idx));
byte[] bytes = s.getImageFromURL(oneFile);
zos.write(bytes, 0, bytes.length);
zos.closeEntry();
idx++;
}
zos.close();
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + filename);// 设置文件名
OutputStream os = response.getOutputStream();
os.write(bos.toByteArray());
os.close();
} catch (
FileNotFoundException ex) {
log.error("FileNotFoundException", ex);
} catch (Exception ex) {
log.error("Exception", ex);
}
}
}