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());
        }
    }
}
相关推荐
tERS ERTS3 分钟前
头歌答案--爬虫实战
java·前端·爬虫
byterun7 分钟前
LangChain4j 完整学习指南:从入门到企业级应用实战,看完这一篇你就是AI应用开发工程师
后端
识君啊9 分钟前
中小厂数据库事务高频面试题
java·数据库·mysql·隔离级别·数据库事务·acid
掘金者阿豪14 分钟前
为什么 LINUX DO 突然这么火?一个程序员拆解背后的5个互联网逻辑
后端
少许极端17 分钟前
算法奇妙屋(四十八)-单调栈
java·算法·单调栈
学习使我健康22 分钟前
Android 本地音乐播放(读取系统媒体库 + MediaPlayer)
java·android-studio
lwx5728022 分钟前
MySQL 数据库自动化备份脚本:从入门到生产实践
数据库·后端
彭于晏Yan30 分钟前
Spring Boot整合WebSocket入门(一)
spring boot·后端·websocket
云烟成雨TD42 分钟前
Spring AI Alibaba 1.x 系列【33】Human-in-the-Loop(人在回路)演示
java·人工智能·spring
今天你TLE了吗44 分钟前
LLM到Agent&RAG——AI概念概述 第五章:Skill
人工智能·笔记·后端·学习