java实现从linux服务器把多个附件打成zip包并返回给前端代码生成
时间: 2023-12-09 22:05:07 浏览: 94
你可以使用Java中的ZipOutputStream类来实现将多个附件打包成Zip文件并返回给前端。以下是一个简单的代码示例:
```java
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ZipServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取要打包的文件列表
String[] fileNames = request.getParameterValues("fileNames[]");
try {
// 设置响应头
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=\"archive.zip\"");
// 创建ZipOutputStream
ServletOutputStream out = response.getOutputStream();
ZipOutputStream zipOut = new ZipOutputStream(out);
// 添加文件到ZipOutputStream
for (String fileName : fileNames) {
File file = new File(fileName);
FileInputStream in = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(file.getName());
zipOut.putNextEntry(zipEntry);
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > 0) {
zipOut.write(buffer, 0, len);
}
in.close();
zipOut.closeEntry();
}
// 关闭ZipOutputStream
zipOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这个代码示例中,我们首先从请求中获取要打包的文件列表,然后设置响应头以告诉浏览器返回的是一个Zip文件,并将ZipOutputStream对象的输出流设置为响应的输出流。接着,我们遍历文件列表,将每个文件添加到ZipOutputStream中。最后,我们关闭ZipOutputStream以确保Zip文件正确地生成并返回给前端。
阅读全文