当前位置: 首页 > article >正文

springboot实现多文件上传

springboot实现多文件上传

代码

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即可)
在这里插入图片描述


http://www.kler.cn/a/562166.html

相关文章:

  • C++ day4 练习
  • 抖音视频如何下载保存去水印
  • 本地大模型编程实战(23)用智能体(Agent)实现基于SQL数据构建问答系统(2)
  • kubernetes中pod spec设置的limits request会转换为哪些参数进行限制
  • [杂学笔记]OSI七层模型作用、HTTP协议中的各种方法、HTTP的头部字段、TLS握手、指针与引用的使用场景、零拷贝技术
  • 形式化数学编程在AI医疗中的探索路径分析
  • 爬虫运行后如何保存数据?
  • 【redis】数据类型之hyperloglog
  • 利用Java爬虫获取VIP商品详情实战案例指南
  • 如何使用深度学习进行手写数字识别(MNIST)
  • 基于Prometheus与Grafana构建实时监控与告警体系,保障微服务稳定性!
  • python如何去除列表末尾的None
  • Nmap网络安全审计
  • 超多目标优化:基于导航变量的多目标粒子群优化算法(NMOPSO)的无人机三维路径规划,MATLAB代码
  • https和http有什么区别
  • kotlin 知识点 七 泛型的高级特性
  • 【gitlab】认识 持续集成与部署
  • Java 值传递
  • python实现基于文心一言大模型的sql小工具
  • Unity Shader Graph 2D - Procedural程序化图形循环加载进度效果