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

相关推荐
Asthenia04125 分钟前
MQ项目接入Retry实践——构造器模式+命令模式+模版方法模式
后端
我命由我1234513 分钟前
34.Java 阻塞队列(阻塞队列架构、阻塞队列分类、阻塞队列核心方法)
java·服务器·开发语言·后端·架构·java-ee·后端开发
猿周LV16 分钟前
JUC (java. util.concurrent) 的常见类及创建新线程的方法等 [Java EE 初阶]
java·开发语言·java-ee
CN.LG18 分钟前
Spring Boot 与@Bean注解搭配场景
java·spring boot·spring
HPF_9921 分钟前
JVM 简单内存结构及例子
java·jvm
m0_7482489424 分钟前
猿创征文 【高级篇】Java 进阶之JVM实战
java·开发语言·jvm
计算机毕设指导628 分钟前
基于Springboot的小说网站【附源码】
java·开发语言·spring boot·后端·mysql·spring·maven
盖世英雄酱5813640 分钟前
延迟5个月的回复:编程式事务的传播行为存在并发问题?
java·后端
V+zmm101341 小时前
智慧物流小程序(论文源码调试讲解)
java·数据库·微信小程序·小程序·毕业设计
月落星还在1 小时前
SpringBoot文件上传实战:存储架构设计与服务器空间优化
服务器·数据库·spring boot