当前位置: 首页 > news >正文

MultipartFile 接口

        MultipartFile 是 Spring Framework 的一部分,它是一个接口,用于处理 HTTP 请求中的文件上传。这个接口提供了访问上传文件的内容、元数据和输入流的方法。

MultipartFile 的主要方法

返回上传文件的 MIME 类型

getContentType();

返回上传文件在客户端的原始文件名

getOriginalFilename():

返回文件的大小,单位为字节

getSize()

指示上传的文件是否为空

isEmpty()

将上传的文件保存到指定的 File 路径

transferTo(File dest)

将上传的文件保存到指定的 Path 路径

transferTo(Path dest)

返回文件内容的 InputStream,可以用于读取文件数据

getInputStream()

返回文件内容的字节数组

getBytes()

代码案例

        以下是一个使用 Spring MVC 的控制器示例,它处理文件上传请求

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());}}
}


http://www.mrgr.cn/news/39953.html

相关文章:

  • 从一到无穷大 #36 Lindorm 宽表:东西互联,南北互联,AI一体
  • 优选驾考系统小程序的设计
  • 香港科技大学新作:速度场如何在复杂城市场景规划中大显身手
  • MySQL那些事(InnoDB架构和存储结构)
  • 怎样才能设计出全面且详细的测试要点?
  • Ollama安装部署CodeGeeX4 - ALL - 9B
  • AI写作赋能数据采集,开启无限可能性
  • Linux系统应用(6)——make与makefile
  • Electrodoc 5.2 专业电工工具集合,支持多种计算器和资料查询!
  • 平安养老险深圳分公司积极开展“金融教育宣传月”活动,展现金融为民新风尚
  • JWT 令牌生成报错
  • 【spring中event】事件简单使用
  • ubutun nginx 安装和解决端口占用问题
  • Artec Leo 3D扫描助力Illumaesthetic公司加速汽车定制
  • 集师专属知识付费小程序搭建 心理咨询小程序搭建
  • AI大模型面试大纲
  • MPS---MP87180芯片layout设计总结
  • 若依拓展开源项目
  • nominatim部署OSM离线地图
  • 数据结构——队列的基本操作