【问题标题】:How can I track file download progress on the back end with Spring Boot?如何使用 Spring Boot 在后端跟踪文件下载进度?
【发布时间】:2018-02-17 09:23:55
【问题描述】:

我有一个 spring boot 应用程序,它有一个返回字符串和文本文件的 rest 控制器。 我想在服务器端跟踪下载进度,并将消息推送到队列。
当使用HttpServlet 工作时,我只是从HttpResponse 对象中得到一个OutputStream 并将字节推送到套接字上,计算进度,如下所示:

    byte[] buffer = new byte[10];
    int bytesRead = -1;
    double totalBytes = 0d;
    double fileSize = file.length();

    while ((bytesRead = inStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, bytesRead);
        totalBytes += bytesRead;
        queueClient.sendMessage(
                "job: " + job + "; percent complete: " + ((int) (totalBytes / fileSize) * 100));

        }

但是,使用 Spring Boot,因为很多事情都发生在幕后,我不能 100% 确定如何处理它。

我才刚刚开始使用 Spring Boot,所以请放轻松! 我的Controller 目前看起来像这样:

@RestController
@RequestMapping("/api/v1/")
public class MyController {

    @Autowired
    QueueClient queue;

    @RequestMapping(value = "info/{id}", method = RequestMethod.GET)
    public String get(@PathVariable long id) {
        queue.sendMessage("Client requested id: " + id);
        return "You requested ID: " + id;
    }

    @RequestMapping(value = "files/{job}", method = RequestMethod.GET)
    public String getfiles(@PathVariable long job) {
        queue.sendMessage("Client requested files for job: " + job);
        return "You requested files for job " + job;
    }
}

我需要将文件从服务器流式传输到客户端,而无需先将整个文件加载到内存中。 Spring REST Controllers 可以做到这一点吗?
如何访问HttpResponse 对象,或者有其他方法吗?

【问题讨论】:

    标签: java spring rest spring-boot io


    【解决方案1】:

    可以获取HttpResponse对象并下载大文件如下:

    @RequestMapping(value = "/files/{job}", method = RequestMethod.GET, produces=MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void downloadFile(@PathVariable("job") String job, HttpServletResponse response) {
    
    //Configure the input stream from the job
        InputStream file = new FileInputStream(fileStoragePath + "\\" + job);
    
        response.setHeader("Content-Disposition", "attachment; filename=\""+job+"\"");
    
    
        int readBytes = 0;
        byte[] toDownload = new byte[100];
        OutputStream downloadStream = response.getOutputStream();
    
        while((readBytes = file.read(toDownload))!= -1){
            downloadStream.write(toDownload, 0, readBytes);
        }
        downloadStream.flush();
        downloadStream.close(); 
    }
    

    【讨论】:

    • 非常感谢!我没有意识到 Spring Boot 会自动填充 HttpServletResponse 如果我只是将它添加为参数!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    相关资源
    最近更新 更多