Java文件上传与下载压缩
文件上传与下载压缩
文件上传:
这是一个通用的本地文件的上传代码,可以将文件类型存储到相应的本地目录下
注:本次演示为存储路径为项目所在的resources目录下,可通过url去访问本地文件数据适用于图片文本等的图片上传组件
// 保存的路径,相对路径,此处为项目resources目录下位置
private String relativePath = "src/main/resources";
@PostMapping(value = "/upload")
@Transactional
@ResponseBody
public void upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
if (ObjectUtil.isNull(file) || StrUtil.isBlank(filename)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "文件或文件名为空");
}
//1.创建文件夹
// 获取resource目录下路径
File directory = new File(relativePath);
//自定义路径
String uploadPath = directory.getCanonicalPath()+ "/static/upload/";
File uploadFolder = new File(uploadPath);
if (!uploadFolder.exists()) {
uploadFolder.mkdirs();
}
//2.保存文件
String filename = file.getOriginalFilename();
//添加随机的UUID,文件重命名
String rename = filename.substring(0, filename.lastIndexOf(".")) + "_" + RandomUtil.randomString(16);
//文件后缀
String suffix = filename.substring(filename.lastIndexOf(".") + 1);
//完整文件名
String longName = rename +"."+ suffix;
file.transferTo(new File(uploadFolder, longName));
//浏览器访问该静态资源路径
String urlPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/upload/" + longName;
//3.存储附件表
Attachments att = new Attachments();
att.setFileName(longName);
att.setPath("/upload/"+longName);
att.setUrlPath(urlPath);
attachementsMapper.insert(att);
}
文件下载并添加到zip中进行下载
@GetMapping(value = "/downloadZip")
@Transactional
public void downloadZip(HttpServletResponse response, HttpServletRequest request) throws IOException {
//1. 设置响应头
response.setCharacterEncoding("utf-8");
response.setContentType("application/oct-stream");
// 返回客户端浏览器的版本号、类型
String agent = request.getHeader("USER-AGENT");
// 设置压缩包的名字,date为时间戳
Instant now = Instant.now();
long timestamp = now.toEpochMilli();
String time = String.valueOf(timestamp);
String downloadName = time + ".zip";
try {
// 针对IE或者以IE为内核的浏览器:
if (agent.contains("MSIE") || agent.contains("Trident")) {
downloadName = URLEncoder.encode(downloadName, StandardCharsets.UTF_8);
} else {
// 非IE浏览器的处理:
downloadName = new String(downloadName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
}
} catch (Exception e) {
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "系统异常");
}
final String charset = ObjectUtil.defaultIfNull(response.getCharacterEncoding(), CharsetUtil.UTF_8);
response.setHeader("Content-Disposition", StrUtil.format("attachment;filename=\"{}\"",
URLUtil.encode(downloadName, CharsetUtil.charset(charset))));
//2.取得文件列表
List<Attachments> attachmentList=Lists.newArrayListWithCapacity(10);
//3.遍历压缩
// 设置压缩流:直接写入response,实现边压缩边下载(@Cleanup用法类似于try-catch异常并主动关闭流)
@Cleanup OutputStream outputStream = response.getOutputStream();
@Cleanup ZipOutputStream zipOs = new ZipOutputStream(outputStream);
// 设置压缩方法
zipOs.setMethod(ZipOutputStream.DEFLATED);
// 遍历文件信息(主要获取文件名/文件路径等)
for (Attachments a : attachmentList) {
String filename = a.getFileName();
String contextPath = "/upload/" + f.getFileName();
File file = new File(contextPath);
Assert.isTrue(file.exists(), "文件不存在");
zipOs.putNextEntry(new ZipEntry(filename));
@Cleanup FileInputStream fs = new FileInputStream(file);
IOUtils.copy(fs, zipOs);
}
}