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());
        }
    }
}
相关推荐
AdSet聚合广告1 小时前
APP广告变现,开发者如何判断对接的广告SDK安全合规?
大数据·后端·算法·安全·uni-app
liuyang-neu2 小时前
黑马点评双拦截器和Threadlocal实现原理
java
csdn_aspnet3 小时前
Java 程序求圆弧段的面积(Program to find area of a Circular Segment)
java·开发语言
野犬寒鸦3 小时前
Redis核心数据结构操作指南:字符串、哈希、列表详解
数据结构·数据库·redis·后端·缓存·哈希算法
无敌小肥0074 小时前
Springboot 整合 WebSocket 实现聊天室功能
spring boot·后端·websocket
Magnum Lehar4 小时前
vulkan游戏引擎vulkan部分的fence实现
java·前端·游戏引擎
on the way 1234 小时前
创建型模式之Factory Method(工厂方法)
android·java·工厂方法模式
无心水4 小时前
【后端高阶面经:MongoDB篇】41、MongoDB 是怎么做到高可用的?
java·开发语言·mongodb·java面试·高可用·后端高阶面经·后端工程师的高阶面经
无心水4 小时前
【后端高阶面经:MongoDB篇】40、怎么优化MongoDB的查询性能?
java·开发语言·mongodb·java面试·后端高阶面经·后端工程师的高阶面经·java高阶面经
gb42152875 小时前
更新时间相差8个小时
java·开发语言