基於解決方案here(對於普通Servlet
),您也可以對基於Spring MVC的控制器執行相同的操作。
@RequestMapping(value = "/export", method = RequestMethod.GET)
public void getFile(OutputStream out) {
FileSystemResource resource = new FileSystemResource("c:\file.csv");
try (ZipOutputStream zippedOUt = new ZipOutputStream(out)) {
ZipEntry e = new ZipEntry(resource.getName());
// Configure the zip entry, the properties of the file
e.setSize(resource.contentLength());
e.setTime(System.currentTimeMillis());
// etc.
zippedOUt.putNextEntry(e);
// And the content of the resource:
StreamUtils.copy(resource.getInputStream(), zippedOut);
zippedOUt.closeEntry();
zippedOUt.finish();
} catch (Exception e) {
// Do something with Exception
}
}
您基於響應OutputStream
(你可以簡單地已經注入法)創建一個ZipOutputStream
。然後爲壓縮的流創建一個條目並寫入它。
而不是OutputStream
你也可以連線HttpServletResponse
,這樣你就可以設置文件的名稱和內容類型。
@RequestMapping(value = "/export", method = RequestMethod.GET)
public void getFile(HttpServletResponse response) {
FileSystemResource resource = new FileSystemResource("c:\file.csv");
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=file.zip");
try (ZipOutputStream zippedOUt = new ZipOutputStream(response.getOutputStream())) {
ZipEntry e = new ZipEntry(resource.getName());
// Configure the zip entry, the properties of the file
e.setSize(resource.contentLength());
e.setTime(System.currentTimeMillis());
// etc.
zippedOUt.putNextEntry(e);
// And the content of the resource:
StreamUtils.copy(resource.getInputStream(), zippedOut);
zippedOUt.closeEntry();
zippedOUt.finish();
} catch (Exception e) {
// Do something with Exception
}
}
是否要在服務器上創建zip文件或在webserver和客戶端瀏覽器之間使用「實時gzip壓縮」? – reto
我想創建一個壓縮文件(來自未壓縮的本地文件)。如果它是'zip'或'gzip'並不重要。 – membersound
請參閱http://stackoverflow.com/questions/26113345/compress-dynamic-content-to-servletoutputstream。同樣的技巧可以用普通的控制器。 –