springboot实现多文件上传

springboot实现多文件上传

代码

java 复制代码
package com.sh.system.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

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

@RestController
@RequestMapping("/filesUpload")
public class FileUploadController {

    // 文件存储路径(可以根据需要修改)
    private static String UPLOADED_FOLDER = "uploads/";


    /*
    *
    * 单文件上传
    */
    @PostMapping("/file")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new ResponseEntity<>("Please select a file to upload.", HttpStatus.BAD_REQUEST);
        }

        try {
            // 获取文件名并添加唯一后缀防止重名
            String fileName = StringUtils.cleanPath(file.getOriginalFilename());
            String uniqueFileName = UUID.randomUUID().toString() + "_" + fileName;

            // 创建文件存储路径
            Path filePath = Paths.get(UPLOADED_FOLDER).toAbsolutePath().normalize();
            Files.createDirectories(filePath);

            // 保存文件到指定路径
            Path targetLocation = filePath.resolve(uniqueFileName);
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

            return ResponseEntity.ok("File uploaded successfully: " + uniqueFileName);
        } catch (IOException ex) {
            return new ResponseEntity<>("Could not upload the file!", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }



    /*
    *
    * 多文件上传
    *
    * */
    @PostMapping("/files")
    public ResponseEntity<String> uploadFiles(@RequestParam("files") List<MultipartFile> files) {
        if (files.isEmpty()) {
            return new ResponseEntity<>("Please select files to upload.", HttpStatus.BAD_REQUEST);
        }

        try {
            for (MultipartFile file : files) {
                // 获取文件名
                String fileName = StringUtils.cleanPath(file.getOriginalFilename());
                // 如果文件名为空或只包含空白字符,则生成一个唯一的文件名
                if (fileName.contains("..") || fileName.isEmpty()) {
                    fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
                }

                // 构建文件路径
                Path filePath = Paths.get(UPLOADED_FOLDER + fileName);
                // 确保上传目录存在
                Files.createDirectories(filePath.getParent());

                // 保存文件到指定路径
                Files.copy(file.getInputStream(), filePath, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
            }

            return new ResponseEntity<>("Files uploaded successfully!", HttpStatus.OK);

        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>("Failed to upload files.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

postman操作截图

1、设置header

2、设置Body(说明:图示为多文件测试,单个文件,只需要设置一个key,value即可)

相关推荐
在努力的前端小白3 小时前
Spring Boot 敏感词过滤组件实现:基于DFA算法的高效敏感词检测与替换
java·数据库·spring boot·文本处理·敏感词过滤·dfa算法·组件开发
bobz9655 小时前
小语言模型是真正的未来
后端
一叶飘零_sweeeet6 小时前
从繁琐到优雅:Java Lambda 表达式全解析与实战指南
java·lambda·java8
DevYK6 小时前
企业级 Agent 开发实战(一) LangGraph 快速入门
后端·llm·agent
艾伦~耶格尔6 小时前
【集合框架LinkedList底层添加元素机制】
java·开发语言·学习·面试
一只叫煤球的猫6 小时前
🕰 一个案例带你彻底搞懂延迟双删
java·后端·面试
最初的↘那颗心6 小时前
Flink Stream API 源码走读 - print()
java·大数据·hadoop·flink·实时计算
冒泡的肥皂7 小时前
MVCC初学demo(一
数据库·后端·mysql
颜如玉7 小时前
ElasticSearch关键参数备忘
后端·elasticsearch·搜索引擎
JH30737 小时前
Maven的三种项目打包方式——pom,jar,war的区别
java·maven·jar