springboot实现多文件上传

news/2025/2/26 12:46:08

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


http://www.niftyadmin.cn/n/5868714.html

相关文章

Ubuntu22.04系统安装Anaconda、CUDA和CUDNN

之前一直在Windows系统下使用Anaconda和CUDA加速&#xff0c;最近需要复现一个算法&#xff0c;文档里面有Linux系统conda构建环境的教程。 本篇博文参考博文&#xff0c;记录自己安装的过程&#xff0c;便于以后需要。 目录 1.Anaconda1.1 安装包下载1.2 安装软件1.3 更新cond…

Mac编译ffmpeg源码并集成到iOS App

编译出iOS静态库 1、下载ffmpeg源码 https://www.ffmpeg.org/download.html#build-mac 下载成功后:看到文件列表如下: 2、在根目录,创建build-ios.sh,内容如下 #!/bin/bash# 设置目标架构 ARCHS=

「爬虫实战分享:如何高效爬取某汽车官方销售排行榜」

本文目录 &#x1f496;前言一、&#x1f4ab;代理IP的作用二、&#x1f4ab;爬虫中的挑战1.代理IP的质量和稳定性2.IP封禁问题3. 反爬虫技术的升级 三、&#x1f4ab;亮数据动态代理&#xff1a;数据采集的可靠伙伴1、真实体验 四、&#x1f4ab;爬虫实战&#xff1a;使用亮数…

dubbo转http方式调用

业务背景&#xff1a;在当前项目下&#xff0c;所有前端请求均通过外层网关转发到后端这边的dubbo服务&#xff0c;现计划去掉网关层&#xff0c;由前端直接http调用后端dubbo。 解决方案&#xff1a;在前端调用方式不变的前提下&#xff0c;后端服务新建controller层&#xf…

安装TortoiseGit时,显示需要安装驱动?!

安装TortoiseGit时&#xff0c;显示需要安装驱动&#xff1f; 原因分析&#xff1a; 出现上述情况&#xff0c;单纯是被捆绑了&#xff0c;TortoiseGit是不需要任何插件 解决方案&#xff1a; 在电脑上选择应用Windows安装程序

VMware中的linux常用指令

常用 Linux 基础命令 文件与目录操作 ls&#xff1a;查看当前目录的文件和子目录&#xff0c;ls -a显示所有文件&#xff0c;包括隐藏文件。cd&#xff1a;切换目录&#xff0c;如 **cd ~** 切换到个人家目录。pwd&#xff1a;查看当前目录。mkdir&#xff1a;创建文件夹&#…

DeepSeek在金融银行的应用方案

1. 引言 随着金融科技的迅猛发展&#xff0c;传统金融银行业面临着前所未有的挑战与机遇。数字化转型已成为金融银行业提升效率、优化客户体验、增强竞争力的必由之路。在这一背景下&#xff0c;DeepSeek作为一款先进的智能解决方案&#xff0c;凭借其强大的数据分析能力、智能…

python-leetcode-字符串解码

394. 字符串解码 - 力扣&#xff08;LeetCode&#xff09; class Solution:def decodeString(self, s: str) -> str:stack []num 0curr_str ""for char in s:if char.isdigit():num num * 10 int(char)elif char [:stack.append((curr_str, num))curr_str, …