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());
        }
    }
}
相关推荐
aiotto资源分享10 小时前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
利威尔xu10 小时前
Go Mutex 饥饿模式:正常模式等待者饿死,1ms 阈值自动切换崩溃
开发语言·后端·面试·golang·并发编程
一条Go11 小时前
边缘 Agent:为什么是它连出来,而不是平台连进去
后端·架构·github
RuoyiOffice11 小时前
SpringBoot3+Vue3 采购到付款:ERP、WMS与财务如何按同一来源协同
java·spring boot·架构·vue
huangfuyk11 小时前
前端融入/转后端避坑指南:AI 时代的安全边界、数据防线与实战细节
后端·ai编程
文丑颜不良啊11 小时前
LeetCode3261~3280题目解析
java·leetcode
代码不停11 小时前
Spring 原理
java·spring
掘金者阿豪11 小时前
GitLab 服务器疑似遭入侵:从 502 故障到 Root 权限异常的完整排查复盘
后端
企业数字化笔记12 小时前
报表上线怎么对账?口径回归、权限抽检与差异定位
java·spring boot·mysql
乌暮12 小时前
少写重复 CRUD:用大白话搞懂 MyBatis-Plus
java·开发语言·spring boot·面试·mybatis