[英]Generating Zip for Download using Zip4j
我嘗試使用Zip4j生成一個zip文件供下載。 但我總是得到錯誤:
2015-05-09 15:56:24.306 ERROR 11748 --- [nio-8080-exec-4] oaccC [。[。[/]。[dispatcherServlet]:servlet [dispatcherServlet]的Servlet.service()與上下文path []引發異常[請求處理失敗; 嵌套異常是java.lang.IllegalStateException:已根據原因為此響應調用了getOutputStream()
調用zout.putNextEntry(file,null)時; 在下面的功能中
public void EmployeeEncyrptedZipFileDownload(HttpServletResponse response, @RequestParam(value = "id", required = true) int employeeId) throws IOException, ZipException
{
//Prepare text file contents
String fileContent = "Hallo Welt";
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment;filename=test.zip");
final StringBuilder sb = new StringBuilder(fileContent);
final ZipOutputStream zout = new ZipOutputStream(response.getOutputStream());
File file = new File("mytext.txt");
zout.putNextEntry(file, null);
byte[] data = sb.toString().getBytes();
zout.write(data, 0, data.length);
zout.closeEntry();
zout.finish();
}
怎么可能,因為putNextEntry函數甚至沒有獲得響應但是已經獲得了全部流?
那是因為,這條線
zout.putNextEntry(file, null);
因為null參數而拋出空指針。 而且,由於我沒有看到你的servlet的其余部分,你的servlet可能會嘗試再次獲取輸出流以處理/拋出此異常。
上面的putNextEntry()調用中的第二個參數是ZipParameters。 如名稱所述,此參數指定各種zip參數,例如,如果zip受密碼保護,或者zip的內容是從文件或輸入流中讀取的,等等。這是必需的參數。
此調用的第一個參數是File對象。 只有在從本地文件流構建zip時才需要這樣做。 如果要從外部流構建zip(例如在您的情況下),則此參數可以為null。 我知道這不是一個好的設計,將在即將發布的版本中修復。
修復您的方案是:
public void EmployeeEncyrptedZipFileDownload(HttpServletResponse response, @RequestParam(value = "id", required = true) int employeeId) throws IOException, ZipException
{
//Prepare text file contents
String fileContent = "Hallo Welt";
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment;filename=test.zip");
final StringBuilder sb = new StringBuilder(fileContent);
final ZipOutputStream zout = new ZipOutputStream(response.getOutputStream());
ZipParameters zipParameters = new ZipParameters();
zipParameters.setSourceExternalStream(true);
zipParameters.setFileNameInZip("mytext.txt");
zout.putNextEntry(null, zipParameters);
byte[] data = sb.toString().getBytes();
zout.write(data, 0, data.length);
zout.closeEntry();
zout.finish();
}
如果有人需要使用郵編庫Zip4j用密碼加密的文件,這里是一個代碼(如提到這里 ):
public void zipFileWithPassword(String fileToZipPath,String password,String zippedFilePath) throws ZipException
{
ZipFile zipFile=new ZipFile(zippedFilePath);
ZipParameters parameters=new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
parameters.setEncryptFiles(true);
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
parameters.setPassword(password);
File fileToZip=new File(fileToZipPath);
log(Severity.INFO,"Creating a ZIP file: %s",fileToZipPath);
zipFile.addFile(fileToZip,parameters);
}
希望我幫助過某個人......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.