java实现将MultipartFile 压缩zip
时间: 2023-10-12 16:19:52 浏览: 295
可以使用Java的ZipOutputStream类来实现将MultipartFile压缩成zip文件的功能。具体实现步骤如下:
1. 创建一个ZipOutputStream对象
```java
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFileName));
```
2. 将MultipartFile的输入流添加到ZipOutputStream中
```java
zipOut.putNextEntry(new ZipEntry(multipartFile.getOriginalFilename()));
IOUtils.copy(multipartFile.getInputStream(), zipOut);
zipOut.closeEntry();
```
3. 关闭ZipOutputStream对象,并返回压缩后的zip文件
```java
zipOut.close();
File zipFile = new File(zipFileName);
return zipFile;
```
完整代码示例:
```java
public static File compress(MultipartFile[] files) throws IOException {
String zipFileName = "compressed.zip";
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFileName));
for (MultipartFile multipartFile : files) {
zipOut.putNextEntry(new ZipEntry(multipartFile.getOriginalFilename()));
IOUtils.copy(multipartFile.getInputStream(), zipOut);
zipOut.closeEntry();
}
zipOut.close();
File zipFile = new File(zipFileName);
return zipFile;
}
```
需要注意的是,需要导入Apache Commons IO库中的IOUtils类。
阅读全文