QQ扫一扫联系
                            
                        
Spring Boot中实现文件上传和下载的实践
在现代的Web应用程序中,文件上传和下载是常见的功能需求。Spring Boot提供了一种简单而强大的方式来处理文件上传和下载,使得开发这些功能变得容易且高效。本文将介绍如何在Spring Boot应用程序中实现文件上传和下载的实践。
<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Apache Commons FileUpload -->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
    </dependency>
</dependencies>
# 文件上传配置
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
在这个示例中,我们配置了最大文件大小为10MB。您可以根据实际需求进行调整。
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/files")
public class FileController {
    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return "文件为空";
        }
        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 获取文件内容类型
            String contentType = file.getContentType();
            // 获取文件大小
            long fileSize = file.getSize();
            // 执行文件上传逻辑
            return "文件上传成功";
        } catch (Exception e) {
            return "文件上传失败: " + e.getMessage();
        }
    }
}
在这个示例中,我们创建了一个FileController,并使用@PostMapping注解来处理文件上传的请求。在uploadFile方法中,我们通过@RequestParam注解将上传的文件绑定到MultipartFile对象上。然后,我们可以获取文件的相关信息,如文件名、内容类型和文件大小。根据实际需求,我们可以执行文件上传的逻辑。
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/files")
public class FileController {
    // 文件上传代码...
    @GetMapping("/download/{fileName}")
    public ResponseEntity<byte[]> downloadFile(@PathVariable String fileName) {
        // 执行文件下载逻辑
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDisposition(ContentDisposition.attachment().filename(fileName).build());
        // 返回文件内容
        return new ResponseEntity<>(fileBytes, headers, HttpStatus.OK);
    }
}
在这个示例中,我们添加了一个@GetMapping方法来处理文件下载的请求。通过@PathVariable注解,我们可以获取要下载的文件名。然后,我们可以执行文件下载的逻辑,并将文件内容封装在ResponseEntity中返回。在响应头中,我们设置了Content-Type为APPLICATION_OCTET_STREAM,表示二进制流类型,以及Content-Disposition为attachment,表示以附件形式下载文件。
通过遵循上述实践,我们可以在Spring Boot应用程序中实现简单且高效的文件上传和下载功能。Spring Boot的集成和自动配置使得开发这些功能变得更加容易。无论是处理用户上传的文件还是提供下载功能,Spring Boot提供了一种便捷的方式来实现文件的上传和下载。