- 我試圖從服務器中存在的固定位置下載zip文件。
- 在我Rest方法中,我只是從客戶端(瀏覽器)傳遞文件名。 (請參閱下面的代碼)。
在我Rest方法中,我將zip文件發送給客戶端。在Chrome中通過Java下載zip文件時沒有.zip擴展名
該文件在瀏覽器中下載沒有任何問題。
我的問題是,壓縮文件在沒有.zip擴展名的瀏覽器上下載。
@RequestMapping(value = "/zip/{filePath}", method = RequestMethod.GET)
public @ResponseBody void downloadZip(@PathVariable("filePath") String filePath, HttpServletRequest request, HttpServletResponse response) throws IOException {
ServletContext context = request.getServletContext();
File downloadFile = new File(filePath);
FileInputStream inputStream = new FileInputStream(downloadFile);
// get output stream of the response
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[(int) downloadFile.length()];
int bytesRead = -1;
// write bytes read from the input stream into the output stream
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
// get MIME type of the file
String mimeType = context.getMimeType(fullPath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);
// set content attributes for the response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
response.setHeader("Content-Disposition",
String.format("attachment; filename=\"%s\"", downloadFile.getName()));
logger.error("Filename = " + downloadFile.getName());
inputStream.close();
outStream.close();
}
PS:該文件被下載到某些機器上使用ZIP和某些沒有ZIP的機器上。我僅在Chrome上進行了測試(根據客戶要求)。 我認爲,Chrome設置存在問題,我需要關注(只是猜測)。
有人可以幫助嗎?
在此先感謝....
更改設置響應頭文件和將文件推送到輸出流之間的順序 - 畢竟頭文件需要先離開。 –
嘗試過,但它不起作用。不管怎麼說,多謝拉。 – krohit
嘗試MIME類型「應用程序/郵編,應用程序/八位字節流」 –