springboot项目开发文件上传与下载

在Spring Boot项目中,可以使用MultipartFile类来处理文件上传和下载操作。

文件上传:

  1. 在Controller类中添加一个处理文件上传的方法,使用@RequestParam注解来接收文件参数。
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
    // 处理文件上传逻辑
    // ...
    return "File uploaded successfully";
}
  1. 在application.properties文件中配置文件上传的最大限制大小。
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
  1. 在前端页面中添加一个文件上传表单,并指定form的enctype为multipart/form-data。
<form action="/upload" method="POST" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" value="Upload" />
</form>

文件下载:

  1. 在Controller类中添加一个处理文件下载的方法,使用@PathVariable注解来接收文件名参数。
@GetMapping("/download/{fileName}")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
    // 获取文件路径
    String filePath = "path/to/files/" + fileName;
    
    // 创建文件资源对象
    Resource resource = new FileSystemResource(filePath);
    
    // 设置响应头信息
    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
    
    // 返回文件资源对象和响应头
    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(resource.getFile().length())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}
  1. 在前端页面中添加一个下载链接,指向下载文件的URL。
<a href="/download/fileName">Download</a>

下面是全部代码和说明:

文件上传的前端需求:

一个包含文件选择按钮的表单,用于选择要上传的文件。

  • 一个提交按钮,用于触发文件上传操作。
  • 可选的进度条或上传状态显示,以显示文件上传的进度或结果。

文件上传的前端代码:

<form id="uploadForm" enctype="multipart/form-data">
    <input type="file" name="file" id="fileInput" />
    <button type="submit" id="uploadButton">Upload</button>
</form>

<div id="progressBar" style="display: none;">
    <div id="progress" style="width: 0%;"></div>
</div>

<script>
    const form = document.querySelector('#uploadForm');
    const fileInput = document.querySelector('#fileInput');
    const uploadButton = document.querySelector('#uploadButton');
    const progressBar = document.querySelector('#progressBar');
    const progress = document.querySelector('#progress');

    form.addEventListener('submit', (e) => {
        e.preventDefault();
        const file = fileInput.files[0];
        const formData = new FormData();
        formData.append('file', file);

        const xhr = new XMLHttpRequest();
        xhr.open('POST', '/upload');
        xhr.upload.addEventListener('progress', (e) => {
            const percent = Math.round((e.loaded / e.total) * 100);
            progress.style.width = percent + '%';
        });

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                console.log('File uploaded successfully');
            }
        };

        xhr.send(formData);
    });
</script>

文件上传的后端需求:

一个处理文件上传的接口,接收文件参数并保存到指定位置。

  • 可选的文件大小限制,以限制上传文件的大小。
  • 可选的文件类型限制,以限制上传文件的类型。

文件上传的后端代码:

@RestController
public class FileUploadController {

    @Value("${upload.path}")
    private String uploadPath;

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 检查文件大小限制
            if (file.getSize() > MAX_FILE_SIZE) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("File size exceeds the limit");
            }

            // 检查文件类型限制
            String contentType = file.getContentType();
            if (!allowedFileTypes.contains(contentType)) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("File type not allowed");
            }

            // 保存文件到指定位置
            String fileName = file.getOriginalFilename();
            Path filePath = Paths.get(uploadPath, fileName);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            return ResponseEntity.ok("File uploaded successfully");
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file");
        }
    }
}

文件下载的前端需求:

一个下载按钮或链接,用于触发文件下载操作。

文件下载的前端代码:

<a href="/download/fileName" download>Download</a>

文件下载的后端需求:

一个处理文件下载的接口,接收文件名参数并返回文件资源。

文件下载的后端代码:

@GetMapping("/download/{fileName}")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
    try {
        // 获取文件路径
        String filePath = "path/to/files/" + fileName;

        // 创建文件资源对象
        Resource resource = new FileSystemResource(filePath);

        // 设置响应头信息
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(resource.getFile().length())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    } catch (IOException e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一花一world

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值