springboot 上传/下载文件

1. 创建文件上传接口

首先,定义一个Controller类来处理文件上传请求。

package com.example.demo.controller;

import com.example.demo.service.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/files")
public class FileUploadController {

    @Autowired
    private FileStorageService fileStorageService;

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        String fileUrl = fileStorageService.storeFile(file);
        return ResponseEntity.status(HttpStatus.CREATED).body(fileUrl);
    }
}

2. 创建文件存储服务

文件存储服务负责将上传的文件保存到指定的目录,并生成访问文件的URL。

package com.example.demo.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
public class FileStorageService {

    @Value("${file.storage.path}")
    private String storagePath;

    @Value("${file.access.url}")
    private String fileAccessUrl;

    public String storeFile(MultipartFile file) {
        // 生成唯一文件名
        String fileName = UUID.randomUUID().toString() + "-" + file.getOriginalFilename();
        Path filePath = Paths.get(storagePath, fileName);

        try {
            // 确保目录存在
            Files.createDirectories(filePath.getParent());
            // 保存文件
            Files.copy(file.getInputStream(), filePath);
        } catch (IOException e) {
            throw new RuntimeException("Could not store file " + fileName, e);
        }

        // 返回文件的访问URL
        return fileAccessUrl + "/" + fileName;
    }
}

3. 配置文件

application.properties中配置文件存储路径和访问URL。

# 文件存储路径
file.storage.path=./uploaded-files

# 文件访问URL
file.access.url=http://localhost:8080/files

4. 配置文件上传限制

可以通过Spring Boot的配置文件来限制上传文件的大小,确保系统的安全和稳定性。

# 单个文件最大大小
spring.servlet.multipart.max-file-size=10MB

# 请求总大小限制
spring.servlet.multipart.max-request-size=20MB

5. 创建文件访问控制

如果需要控制对文件的访问权限,可以在Controller中添加相应的权限检查逻辑。

@GetMapping("/download/{fileName}")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
    Path filePath = Paths.get(storagePath, fileName);
    Resource resource = new FileSystemResource(filePath.toFile());
    if (!resource.exists()) {
        throw new ResourceNotFoundException("File not found: " + fileName);
    }
    return ResponseEntity.ok()
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}

6. 异常处理

为文件上传过程中的异常情况提供适当的处理。

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> handleRuntimeException(RuntimeException ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                             .body("File upload failed: " + ex.getMessage());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值