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

相关推荐
郭庆汝17 分钟前
Windows安装java流程
java·windows·android studio
Yvonne爱编码22 分钟前
后端编程开发路径:从入门到精通的系统性探索
java·前端·后端·python·sql·go
迦蓝叶37 分钟前
JAiRouter 0.8.0 发布:Docker 全自动化交付 + 多架构镜像,一键上线不是梦
java·人工智能·网关·docker·ai·架构·自动化
im_AMBER1 小时前
Leetcode 18 java
java·算法·leetcode
Q_Q19632884751 小时前
python+springboot大学生心理测评与分析系统 心理问卷测试 自动评分分析 可视化反馈系统
开发语言·spring boot·python·django·flask·node.js·php
Android技术之家1 小时前
Kotlin与Compose:Android开发的现代化变革
android·java·开发语言·kotlin
失散131 小时前
分布式专题——10.3 ShardingSphere实现原理以及内核解析
java·分布式·架构·shardingsphere·分库分表
十八旬1 小时前
【超简单】后端入门案例-基于SpringBoot+MyBatis-plus+MySQL图书管理系统
java·开发语言·idea·intellij idea·项目实战
zhz52142 小时前
Spring Boot + Redis 缓存性能优化实战:从5秒到毫秒级的性能提升
java·spring boot·redis·缓存·vue
lifallen2 小时前
Hadoop MapOutputBuffer:Map高性能核心揭秘
java·大数据·数据结构·hadoop·算法·apache