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());
        }
    }
}
相关推荐
百度Geek说2 分钟前
项目级效能提升一站式交付最佳实践
后端
今天你TLE了吗13 分钟前
通过RocketMQ延时消息实现优惠券等业务MySQL当中定时自动过期
java·spring boot·后端·学习·rocketmq
胡楚昊14 分钟前
CTF SHOW逆向
java·服务器·前端
Gundy15 分钟前
构建一个真正好用的简单搜索引擎
后端
疯狂的程序猴20 分钟前
构建面向复杂场景的 iOS 应用测试体系 多工具协同下的高质量交付实践
后端
大巨头28 分钟前
C# 中如何理解泛型
后端
烤麻辣烫31 分钟前
黑马程序员苍穹外卖(新手)DAY12
java·开发语言·学习·spring·intellij-idea
BD_Marathon34 分钟前
【IDEA】常用插件——3
android·java·intellij-idea
用户9924410315636 分钟前
TRAE SOLO实战录:AI应用可观测性与风险管控的破局之道
后端
Dr丶net39 分钟前
🔥NestJS 接口文档神器!nestjs-knife4j-plus 让 Swagger 颜值与功能双飞跃
后端