【问题标题】:Download a file in browser using java /spring使用 java /spring 在浏览器中下载文件
【发布时间】:2015-10-27 18:38:17
【问题描述】:

我正在尝试使用 java 在浏览器中下载文件。问题是我在代码中没有任何错误。但该文件未在浏览器中下载。 我已经转发了这个网站:http://www.codejava.net/frameworks/spring/spring-mvc-sample-application-for-downloading-file

        ServletContext context = request.getServletContext();
        String appPath = context.getRealPath("");
        String filePat="pat of the file";
        File downloadFile = new File(filePath);
        System.out.println("downloadFile path: "+ filePath);
        FileInputStream inputStream = new FileInputStream(downloadFile);

     // 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);

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

        // set headers for the response
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"",downloadFile.getName());
        response.setHeader(headerKey, headerValue);

        OutputStream outStream = response.getOutputStream();

        byte[] buffer = new byte[BUFFER_SIZE];
        System.out.println("buffer: "+ buffer.length);
        int bytesRead = -1;

        // write bytes read from the input stream into the output stream
        int counter=0;
        while ((bytesRead = inputStream.read(buffer))!=-1  ) {
            counter++;
            System.out.println("counter: "+ counter+ "bytesRead:"+bytesRead);
            outStream.write(buffer, 0, bytesRead);
        }

        inputStream.close();
        outStream.close();

【问题讨论】:

  • 代码有两个幻数,写代码坏了。如果我是你,我会从其他网站复制/粘贴代码。
  • 我添加了 1895 只是为了检查。由于计数器值 > 1896 给出了 writebeyondcontent 长度错误。

标签: java spring servlets httpresponse


【解决方案1】:

这可能是因为您在内容长度上增加了 1000 个字节。因此,浏览器实际上正在等待获取 Content-Length 标头中提到的所有字节。

【讨论】:

  • 写代码还有个bug,写的是buffer.length字节而不是bytesRead字节。
  • 我现在已经删除了那 1000 个额外的字节。但没有运气。我也更新了代码 sn-p。
  • 您应该尝试使用现有的库。 stackoverflow.com/questions/1442893/…
  • 嘿,我发现,进入浏览器的数据,但是作为一个流。意味着我可以在 ajax 调用的成功块中看到文件数据。但要求是在浏览器中下载文件...
  • 感谢 Ramesh,Gimby 澄清了 java 代码。我试图在 javascript 中从 ajax 调用下载,但我知道它不可行。所以使用了 window.location.href 并且我的代码运行良好。我在此链接“stackoverflow.com/questions/23775503/…”中分享了我的代码....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-09
  • 1970-01-01
  • 2014-10-27
  • 2022-06-16
  • 2018-05-21
  • 1970-01-01
  • 2018-11-05
相关资源
最近更新 更多