Java文件下载 - 下载的文件大小始终为零Kb

时间:2017-10-03 05:13:31

标签: java file download

我编写了一个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();
        }
    }

我没有任何例外。请帮忙。 提前谢谢。

2 个答案:

答案 0 :(得分:0)

response.setContentLength((int) downloadFile.length());

删除它。容器将自动设置它。

int bytesRead = -1;

您不需要初始化此变量。它将在下一行中分配。

答案 1 :(得分:0)

感谢您的帮助。我发现我的内容处理标题存在问题。我只传递了没有扩展名的文件名。当我通过完整的文件名时,它完美地工作。文件的大小和扩展是正确的。