我从 mkyong 获得了以下代码,用于在本地压缩文件。但是,我的要求是在服务器上压缩文件并需要下载它。任何人都可以帮忙吗?
代码写入zip文件:
public void zipFiles(File contentFile, File navFile)
{
byte[] buffer = new byte[1024];
try{
// i dont have idea on what to give here in fileoutputstream
FileOutputStream fos = new FileOutputStream("C:\\MyFile.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze= new ZipEntry(contentFile.toString());
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(contentFile.toString());
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
zos.closeEntry();
//remember close it
zos.close();
System.out.println("Done");
}catch(IOException ex){
ex.printStackTrace();
}
}
我可以在 fileoutputstream 中提供什么? contentfile 和 navigationfile 是我从代码创建的文件。
如果你的服务器是servlet容器,只需写一个HttpServlet
它负责压缩和提供文件。
您可以将 servlet 响应的输出流传递给构造函数ZipOutputStream
并且 zip 文件将作为 servlet 响应发送:
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
不要忘记在压缩之前设置响应 mime 类型,例如:
response.setContentType("application/zip");
全图:
public class DownloadServlet extends HttpServlet {
@Override
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=data.zip");
// You might also wanna disable caching the response
// here by setting other headers...
try ( ZipOutputStream zos = new ZipOutputStream(response.getOutputStream()) ) {
// Add zip entries you want to include in the zip file
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)