从具有恢复支持的弹簧控制器下载文件

时间:2013-05-09 03:50:37

标签: java spring download resume-download

Downloading a file from spring controllers

以上是原始文章,但我希望获得简历支持,意味着我可以首先下载51%,然后在其他时间再下载49%。

环境tomcat 7.0.39

我尝试了一些,但仍然失败了。

这是我的代码,或者您可以分享您的代码

            InputStream fis =new FileInputStream(filepath+file_name);

            response.setHeader("Accept-Ranges", "bytes");
            long length = (int) new File(filepath+file_name).length();
            long start = 0;

            if (request.getHeader("Range") != null) 
            {
                response.setStatus(javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT);// 206
                start = Long.parseLong(request.getHeader("Range")
                        .replaceAll("bytes=", "").replaceAll("-", ""));
            }

            response.setHeader("Content-Length", new Long(length - start).toString());
            if (start != 0) 
            {
                response.setHeader("Content-Range", "bytes "
                        + new Long(start).toString() + "-"
                        + new Long(length - 1).toString() + "/"
                        + new Long(length).toString());
            }

            response.setContentType("application/octet-stream");

            fis.skip(start);
            byte[] b = new byte[1024];
            int i;
            while ((i = fis.read(b)) != -1) {
                response.getOutputStream().write(b, 0, i);
                response.flushBuffer();
            }
            fis.close();

已修复,这是我编辑的版本

long length = (int) new File(filepath+file_name).length();
                long start = 0;
                response.setHeader("Accept-Ranges", "bytes");
                response.setStatus(javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT);// 206
                if (request.getHeader("Range") != null) 
                {
                    int x = request.getHeader("Range").indexOf("-");
                    start = Long.parseLong(request.getHeader("Range").substring(0, x)
                            .replaceAll("bytes=", ""));
                }
                response.setHeader("Content-Length", new Long(length - start).toString());

                if(start == 0)
                    response.setHeader("Content-Range", "bytes 0-"        +new Long(length - 1).toString()+"/"+length);
                else
                    response.setHeader("Content-Range", "bytes "+start+"-"+new Long(length - 1).toString()+"/"+length);
                fis.skip(start);
                byte[] b = new byte[1024];
                int i;
                while ((i = fis.read(b)) != -1) {
                    response.getOutputStream().write(b, 0, i);
                    response.flushBuffer();
                }
                fis.close();

1 个答案:

答案 0 :(得分:2)

我构建了一个使用带有或不带Spring的HTTP字节范围的解决方案。 如果您有兴趣,请查看https://gist.github.com/davinkevin/b97e39d7ce89198774b4

这有助于我在主要使用@RestController

的Spring应用程序中使用它