MultipartFile 接口

MultipartFile 是 Spring Framework 的一部分,它是一个接口,用于处理 HTTP 请求中的文件上传。这个接口提供了访问上传文件的内容、元数据和输入流的方法。

MultipartFile 的主要方法

返回上传文件的 MIME 类型

getContentType();

返回上传文件在客户端的原始文件名

getOriginalFilename():

返回文件的大小,单位为字节

getSize()

指示上传的文件是否为空

isEmpty()

将上传的文件保存到指定的 File 路径

transferTo(File dest)

将上传的文件保存到指定的 Path 路径

transferTo(Path dest)

返回文件内容的 InputStream,可以用于读取文件数据

getInputStream()

返回文件内容的字节数组

getBytes()

代码案例

以下是一个使用 Spring MVC 的控制器示例,它处理文件上传请求

java 复制代码
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/api/files")
public class FileUploadController {

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile multipartFile) {
        if (multipartFile.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("文件不能为空");
        }

        try {
            // 构建文件保存路径
            String fileName = multipartFile.getOriginalFilename();
            Path path = Paths.get("uploads").resolve(Paths.get(fileName));
            File destinationFile = path.toFile();

            // 确保目录存在
            if (!destinationFile.getParentFile().exists()) {
                destinationFile.getParentFile().mkdirs();
            }

            // 保存文件
            multipartFile.transferTo(destinationFile);

            return ResponseEntity.ok("文件上传成功,保存路径:" + destinationFile.getAbsolutePath());
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败:" + e.getMessage());
        }
    }
}
相关推荐
Oneslide15 分钟前
sudo免密权限配置不生效
后端
站大爷IP23 分钟前
为什么Python不用var或let声明变量?
后端
赴星半途25 分钟前
NestJS实战-创建AuthService
后端
北冥有鱼26 分钟前
mqtt 测试
前端·后端
代码丰27 分钟前
使用 TtlExecutors 解决线程池中的 ThreadLocal 上下文丢失问题
后端
阿祖zu1 小时前
别再优化 RAG 了,适配 Agent 的 LLM Wiki 知识库理念
前端·后端·aigc
昵称为空C1 小时前
手撸一个动态 SQL 执行引擎:不重启服务,在线增删改查任意数据库
spring boot·后端
用户8356290780512 小时前
用 Python 自动化 PowerPoint 演讲者备注添加
后端·python
神奇小汤圆2 小时前
科研神器再升级!Claude Code 全套 Skills,16 大科研场景全覆盖!
后端