How to use Springboot to implement file upload and download, and add the function of real-time progress bar to it

File upload and download are very basic functions in web development, but in actual development, we often need to display the progress of file upload or download in real time. This article will introduce how to use Springboot to implement file upload and download, and add the function of real-time progress bar to it.

File Upload

Add Maven dependencies

First, we need to add the following Maven dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>

Among them, spring-boot-starter-web is one of the dependencies provided by Spring Boot for building web applications, and commons-fileupload is a popular Java file upload library.

Create HTML form

Next, we need to create an HTML form to submit the file. In this form, we can use elements to select files to upload and elements to submit the form.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>File Upload</title>
</head>
<body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file"/>
        <br/>
        <input type="submit" value="Upload"/>
    </form>
</body>
</html>

In this form, we set the action attribute of the form to "/upload", which is the URL where we will handle the upload request.

Implement file upload

In Springboot, you can use the org.springframework.web.multipart.MultipartFile class to process uploaded files. We can write a Controller to receive and process uploaded files:

@RestController
public class UploadController {
    
    

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {
    
    
        // do something with the file
        return "success";
    }
}

In the above code, we use the @RequestParam annotation to specify the parameter name of the file upload, and save the file to disk or perform other operations. Finally, we return a simple string as the response content.

add progress bar

In order to realize the upload progress bar function, we need to use JavaScript and Ajax to achieve. Specifically, we can use the XMLHttpRequest object to send an asynchronous request, and update the progress bar in real time during the upload process.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>File Upload</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
        $(function () {
      
      
            $("form").submit(function (event) {
      
      
                event.preventDefault();
                var formData = new FormData($(this)[0]);

                $.ajax({
      
      
                    xhr: function () {
      
      
                        var xhr = new window.XMLHttpRequest();
                        xhr.upload.addEventListener("progress", function (evt) {
      
      
                            if (evt.lengthComputable) {
      
      
                                var percentComplete = evt.loaded / evt.total;
                                console.log(percentComplete);
                                $("#progress").css("width", percentComplete * 100 + "%");
                            }
                        }, false);
                        xhr.addEventListener("progress", function (evt) {
      
      
                            if (evt.lengthComputable) {
      
      
                                var percentComplete = evt.loaded / evt.total;
                                console.log(percentComplete);
                                $("#progress").css("width", percentComplete * 100 + "%");
                            }
                        }, false);
                        return xhr;
                    },
                    type: "POST",
                    url: "/upload",
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (data) {
      
      
                        alert("Upload complete!");
                    }
                });
            });
        });
    </script>
</head>
<body>
<form>
    <input type="file" name="file"/>
    <br/>
    <button type="submit">Upload</button>
</form>
<div style="background-color: #ddd; height: 20px; width: 0%;" id="progress"></div>
</body>
</html>

In the code above, we've used jQuery to send the XHR request and update the progress bar during the upload. Specifically, we added a progress event handler to xhr.upload and the xhr object to update the progress bar in real time while the file is being uploaded.

Download Document

Implement file download

To implement file download, we need to write a Controller to handle the download request, and use the org.springframework.core.io.Resource class to return the file to the client as the response content.

@RestController
public class DownloadController {
    
    

    @GetMapping("/download")
    public ResponseEntity<Resource> download() throws IOException {
    
    
        Resource file = new FileSystemResource("/path/to/file");

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getFilename());

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }
}

In the above code, we use the @GetMapping annotation to specify the URL that handles the download request, and use the org.springframework.core.io.Resource class to read the file content. Finally, we return the file to the client as the response content.

add progress bar

The function of adding a download progress bar is similar to the upload progress bar, we can still use the XMLHttpRequest object and JavaScript to achieve. Specifically, we can send an asynchronous request to the Controller and update the progress bar in real time during the download process.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>File Download</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
        $(function () {
      
      
            $("#download").click(function (event) {
      
      
                event.preventDefault();

                var xhr = new XMLHttpRequest();
                xhr.open("GET", "/download", true);
                xhr.responseType = "blob";

                xhr.onload = function () {
      
      
                    if (xhr.status === 200) {
      
      
                        var contentType = xhr.getResponseHeader("Content-Type");
                        var contentDisposition = xhr.getResponseHeader("Content-Disposition");

                        var blob = new Blob([xhr.response], {
      
      type: contentType});

                        var link = document.createElement("a");
                        link.href = window.URL.createObjectURL(blob);
                        link.download = contentDisposition.split("=")[1];
                        link.click();
                    }
                };

                xhr.addEventListener("progress", function (evt) {
      
      
                    if (evt.lengthComputable) {
      
      
                        var percentComplete = evt.loaded / evt.total;
                        console.log(percentComplete);
                        $("#progress").css("width", percentComplete * 100 + "%");
                    }
                }, false);
                xhr.send();
            });
        });
    </script>
</head>
<body>
<button id="download">Download</button>
<div style="background-color: #ddd; height: 20px; width: 0%;" id="progress"></div>
</body>
</html>

In the above code, we have used jQuery to send the XHR request and update the progress bar while the download is in progress. Specifically, we added a progress event handler to the xhr object to update the progress bar in real time while the file is downloading.

in conclusion

This article introduces how to use Springboot to implement file upload and download, and add the function of real-time progress bar to it. When uploading and downloading files, we used the XMLHttpRequest object and JavaScript to implement a real-time progress bar. This feature can help users better understand the progress of file uploads and downloads and improve user experience.

Guess you like

Origin blog.csdn.net/weixin_43025343/article/details/131865033