SoFunction
Updated on 2025-03-08

Spring Boot implements the function of compressing and downloading files

In web applications, file download function is a common requirement, especially when you need to provide users with downloading various types of files. This article will demonstrate how to use the Spring Boot framework to implement a simple and powerful file download function. We will create a RESTful API through which users can download ZIP compressed files.

1. Create a Spring Boot project

First, make sure you have created a Spring Boot project and added the required dependencies to the project. In this example, we will use Spring Boot's web module and Spring's MVC framework.

2. Write a download controller

Create a name calledDownloadController RESTful controller for processing file download requests. In this controller, we will define adownloadStudentWork Method, used to download ZIP compressed files of students' works. Specific file flow sources and specific business.

@RestController
@RequestMapping("/download")
public class DownloadController {
    @GetMapping("/studentWork")
    public ResponseEntity<StreamingResponseBody> downloadStudentWork() {
        HttpHeaders headers = new HttpHeaders();
        (MediaType.APPLICATION_OCTET_STREAM);
        String encodedFileName = "Title of work - Student name.zip";
        try {
            encodedFileName = (encodedFileName, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException e) {
            ();
        }
        ("attachment", encodedFileName);
        StreamingResponseBody responseBody = outputStream -> {
            try (ZipOutputStream zipOut = new ZipOutputStream(outputStream)) {
                // Assume this is the video file stream of the student's work                InputStream videoStream = getStudentVideoStream();
                addToZip(zipOut, videoStream, "Work video.mkv");
                // Add more attachments, if any                ();
            } catch (IOException e) {
                // Handle exceptions            }
        };
        return new ResponseEntity<>(responseBody, headers, );
    }
    private void addToZip(ZipOutputStream zipOut, InputStream inputStream, String fileName) throws IOException {
        ZipEntry zipEntry = new ZipEntry(fileName);
        (zipEntry);
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = (buffer)) != -1) {
            (buffer, 0, bytesRead);
        }
        ();
        ();
    }
    // Get file stream    private InputStream getStudentVideoStream() throws FileNotFoundException {
        // Attachment information        FileInputStream inputStream = new FileInputStream("C:\\Users\\28111\\Videos\\2023-09-14 ");
        return inputStream;
    }
}

3. Set HTTP response header

existdownloadStudentWork In the method, we set the HTTP response header to tell the browser that the response is a downloadable binary file. We also URL encode the file name to make sure that special characters in the file name do not cause problems.

4. Create a ZIP file and add content

Using JavaZipOutputStream Class, we create a ZIP file and add the content of the student's work to it. In the example, we add a hypothetical student work video file.

5. Provide download stream

We useStreamingResponseBody to provide a stream of downloaded files so that files can be transferred to the client block by block. This allows large files to be processed effectively without loading the entire file into memory.

6. Complete example

The above is the general structure of the code, which you can implement in your project. Please make sure to adjust the file path and name according to your needs.

7. Test file download

Finally, run your Spring Boot application and access/download/studentWork Endpoint, you will be able to download the ZIP file of the student's work.

in conclusion

By using Spring Boot, we can easily implement a powerful file download feature. You can extend this example as needed, adding more attachments or custom features to suit your application needs.

This is the article about Spring Boot's compression and downloading files. For more related Spring Boot file compression and download content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!