我有一个 spring boot 应用程序,它有一个返回字符串和文本文件的 rest Controller 。
我想在服务器端跟踪下载进度,并将消息推送到队列。
当使用 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 Controller
是否可行?
我如何访问 HttpResponse
对象,或者有其他方法吗?
最佳答案
可以获取 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();
}
关于java - 如何使用 Spring Boot 在后端跟踪文件下载进度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46116672/