处理文件上传和下载请求

​1. 类注解与全局配置​
​​@RestController​​:声明这是一个 REST 风格的控制器,所有方法返回数据(而非视图)。
​​@RequestMapping("/files")​​:所有请求的根路径为 /files。
​​UPLOAD_ROOT​​:上传文件的存储路径,基于项目根目录下的 uploads 文件夹。

点击查看代码
@RestController
@RequestMapping("/files")
public class FileUploadController {
    private static final String UPLOAD_ROOT = System.getProperty("user.dir") + "/uploads/";
}
​2. 普通文件上传接口 (/upload)​
点击查看代码
@PostMapping("/upload")
public ResponseEntity<Map<String, Object>> uploadFile(@RequestParam("file") MultipartFile file) {
    // 校验文件是否为空
    if (file.isEmpty()) {
        result.put("code", 400);
        result.put("msg", "文件不能为空");
        return ResponseEntity.badRequest().body(result);
    }

    // 生成唯一文件名(时间戳 + 原始文件名)
    String originalFilename = file.getOriginalFilename();
    String safeFileName = FileUtil.getName(originalFilename); // 去除路径部分
    String storedFilename = Instant.now().toEpochMilli() + "_" + safeFileName;

    // 创建上传目录并保存文件
    Path uploadPath = Paths.get(UPLOAD_ROOT);
    FileUtil.mkdir(uploadPath.toString());
    Path targetPath = uploadPath.resolve(storedFilename);
    FileUtil.writeBytes(file.getBytes(), targetPath.toFile());

    // 生成下载链接(URL 编码文件名)
    String encodedFileName = URLUtil.encode(storedFilename);
    result.put("url", "http://localhost:8080/files/download/" + encodedFileName);
    return ResponseEntity.ok(result);
}
3. 文件下载接口 (/download/{fileName})​
点击查看代码
@GetMapping("/download/{fileName}")
public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException {
    String realPath = UPLOAD_ROOT + fileName;

    // 检查文件是否存在
    if (!FileUtil.exist(realPath)) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "文件不存在");
        return;
    }

    // 设置响应头(强制下载)
    ContentDisposition contentDisposition = ContentDisposition.attachment()
            .filename(fileName, StandardCharsets.UTF_8)
            .build();
    response.setHeader("Content-Disposition", contentDisposition.toString());

    // 写入文件内容到响应流
    try (OutputStream os = response.getOutputStream()) {
        os.write(FileUtil.readBytes(realPath));
        os.flush();
    }
}
4. 富文本编辑器文件上传接口 (/wang/upload)
点击查看代码
@PostMapping("/wang/upload")
public Map<String, Object> wangEditorUpload(MultipartFile file) {
    // 生成唯一标识符和时间戳文件名
    String flag = System.currentTimeMillis() + "";
    String fileName = file.getOriginalFilename();
    String storedFileName = flag + "-" + fileName;

    // 保存文件
    String filePath = System.getProperty("user.dir") + "/uploads/";
    FileUtil.writeBytes(file.getBytes(), filePath + storedFileName);

    // 返回符合 wang-editor 要求的格式
    Map<String, Object> resMap = new HashMap<>();
    resMap.put("errno", 0);
    resMap.put("data", Collections.singletonList(
        new HashMap<String, String>() {{
            put("url", "http://localhost:8080/files/download/" + storedFileName);
        }}
    ));
    return resMap;
}
posted @ 2025-04-08 23:23  雨花阁  阅读(57)  评论(0)    收藏  举报