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());
        }
    }
}
相关推荐
毕设源码-邱学长3 小时前
【开题答辩全过程】以 高校就业分析与可视化系统为例,包含答辩的问题和答案
java·eclipse
橙序员小站3 小时前
Springboot3.0并不能拯救你的屎山
java·后端·架构
憧憬少3 小时前
通过切换Service实现类来切换看板数据来源
java·spring boot
YJlio3 小时前
Active Directory 工具学习笔记(10.13):AdRestore——把误删“拉回现场”的最快姿势
java·笔记·学习
武子康3 小时前
大数据-182 Elasticsearch 倒排索引底层拆解:Terms 字典、FST、SkipList 与 Lucene 索引文件
大数据·后端·elasticsearch
未来影子3 小时前
Java估计Agent领域新杀出一匹黑马(agentscope-java)
后端
小黄编程快乐屋4 小时前
Python 期末复习知识点汇总
java·服务器·python
千寻技术帮4 小时前
10400_基于Springboot的职业教育管理系统
java·spring boot·后端·毕设·文档·职业教育
Non importa4 小时前
用滑动窗口代替暴力枚举:算法新手的第二道砍
java·数据结构·c++·学习·算法·leetcode·哈希算法
涛声依旧Cjt4 小时前
Spring AOP实战--优雅的对出参进行脱敏
java·spring·springaop 实战·aop 优雅脱敏·spring 脱敏