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即可)

相关推荐
Tracy-222 小时前
啥是Spring,有什么用,既然收费,如何免费创建SpringBoot项目,依赖下载不下来的解决方法,解决99%问题!
java·spring
未定义.2213 小时前
Java设计模式实战:策略模式在SimUDuck问题中的应用
java·设计模式·策略模式
码熔burning4 小时前
【NIO番外篇】之组件 Channel
java·nio·channel
东阳马生架构4 小时前
Sentinel源码—1.使用演示和简介
后端
卡尔曼的BD SLAMer5 小时前
问题 | 针对SSM(Spring + Spring MVC + MyBatis)框架的去Spring MVC强化版学习路线
java·spring·mvc·mybatis
zhuyasen5 小时前
首个与AI深度融合的Go开发框架sponge,解决Cursor/Trae等工具项目级开发痛点
后端·低代码·go
春生野草5 小时前
0413-多态、Object类方法、访问权限修饰符、装箱拆箱、128陷阱
java·开发语言
Json____5 小时前
springboot框架集成websocket依赖实现物联网设备、前端网页实时通信!
前端·spring boot·websocket·实时通信
烁3475 小时前
每日一题(小白)暴力娱乐篇25
java·数据结构·算法·娱乐
烁3475 小时前
每日一题(小白)暴力娱乐篇26
java·开发语言·算法·娱乐