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());
        }
    }
}
相关推荐
计算机毕设VX:Fegn08953 分钟前
计算机毕业设计|基于springboot + vue小区人脸识别门禁系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
yaoxin52112315 分钟前
279. Java Stream API - Stream 拼接的两种方式:concat() vs flatMap()
java·开发语言
坚持学习前端日记30 分钟前
2025年的个人和学习年度总结以及未来期望
java·学习·程序人生·职场和发展·创业创新
Cosmoshhhyyy32 分钟前
《Effective Java》解读第29条:优先考虑泛型
java·开发语言
Chen不旧44 分钟前
java基于reentrantlock/condition/queue实现阻塞队列
java·开发语言·signal·reentrantlock·await·condition
寒水馨1 小时前
com.github.oshi : oshi-core 中文文档(中英对照·API·接口·操作手册·全版本)以6.4.0为例,含Maven依赖、jar包、源码
java·后端
0和1的舞者1 小时前
SpringBoot日志框架全解析
java·学习·springboot·日志·打印·lombok
踏浪无痕1 小时前
CommitLog顺序写 —— 为什么RoceketMQ所有消息都往一个文件追加?
后端·面试·rocketmq
武子康1 小时前
大数据-200 决策树信息增益详解:信息熵、ID3 选特征与 Python 最佳切分实现
大数据·后端·机器学习
小毅&Nora1 小时前
【Java线程安全实战】② ConcurrentHashMap 源码深度拆解:如何做到高性能并发?
java·安全·多线程