How can I track the progress of loading files on the back panel using Spring Boot?

I have a spring boot application, it has a rest controller that returns strings and text files. I want to monitor server-side download progress and send messages to the queue.
When working with HttpServletI just got OutputStreamfrom the object HttpResponseand pushed bytes on the socket, calculating the progress as they appeared:

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

        }

However, with spring boot, since a lot of things happen under the hood, I'm not 100% sure how to approach it.

I just started with spring boot, so it's easy on me! My Controllernow looks like this:

@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 s?
HttpResponse, ?

+4
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(); 
}
+2

Source: https://habr.com/ru/post/1685305/


All Articles