[英]Java File Download - Downloaded file size is always zero Kb
我編寫了一個 java 控制器來處理來自服務器的任何下載請求。 我的文件存在於服務器中,但是我每次都下載 0 kB 文件。 文件正在下載,但大小始終為 0 Kb。 請幫我。 這是我的代碼 -
@RequestMapping(value="/downloadFile/{docId}")
public void getDownloadFile(@PathVariable(value = "docId") Integer docId, HttpServletResponse response) throws Exception {
String userName = getUserName();
try {
DocVault documentsVault = documentsVaultRepository.findDocumentAttachment(docId);
String fileName = documentsVault.getDocumentName();
int customerId = documentsVault.getCustomerId();
Map<Integer, String> customerInfo = cspUtils.getCustomersInfo(userName);
Set<Integer> customerIds = customerInfo.keySet();
for (int custId : customerIds) {
if (custId == customerId) {
String path = env.getProperty("doc.rootfolder") + File.separator + documentsVault.getFileName();
service.downloadFile(fileName, path, response);
} else {
logger.info("Customer not linked to user");
}
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
執行 -
public void downloadFile(String fileName, String path, HttpServletResponse response) {
try {
File downloadFile = new File(path);
FileInputStream inputStream = new FileInputStream(downloadFile);
response.setContentLength((int) downloadFile.length());
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
// get output stream of the response
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
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);
}
inputStream.close();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
我沒有得到任何例外。 請幫忙。 先感謝您。
response.setContentLength((int) downloadFile.length());
去掉這個。 容器會自動設置它。
int bytesRead = -1;
您不需要初始化此變量。 它在下一行分配。
感謝您的幫助。 我發現我的 Content Disposition 標頭有問題。 我只傳遞沒有擴展名的文件名。 當我傳遞完整的文件名時,它工作得很好。 文件的大小和擴展名是正確的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.