springBoot中文件上传功能Api
springBoot中文件上传功能Api
01) 实现工具类FileUtil
package com.example.fei.common.utils; import org.springframework.web.multipart.MultipartFile; import java.io.*; //文件上传工具类 public class FileUtil { public static void uploadFile(byte[] file,String filePath,String fileName) throws IOException { File targetFile = new File(filePath); if (!targetFile.exists()) { // 创建目录 targetFile.mkdirs(); } FileOutputStream out = new FileOutputStream(filePath + fileName); out.write(file); out.flush(); out.close(); } public static void uploadFile2(InputStream fileStream, String filePath, String fileName) throws IOException { File targetFile = new File(filePath); if (!targetFile.exists()) { // 创建目录 targetFile.mkdirs(); } FileOutputStream out = new FileOutputStream(filePath + fileName); //开始复制 int i = 0; byte[] bytes = new byte[1024]; while((i = fileStream.read(bytes))!=-1) { out.write(bytes, 0, i); } out.close(); fileStream.close(); } // 采用MultipartFile的transfer() 实现上传 public static void uploadFile3(MultipartFile uploadFile, String filePath, String fileName) throws IOException { File targetFile = new File(filePath + fileName); uploadFile.transferTo(targetFile); } }
02) 在 Controller 中写方法

package com.example.fei.controller; import com.example.fei.common.utils.FileUtil; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @RestController @RequestMapping("/file") public class FileController { // 上传文件 @PostMapping("upload") public void upload(@RequestParam("file") MultipartFile file) { // String contentType = file.getContentType(); // 获取文件类型 String fileName = file.getOriginalFilename(); // 图片名字 String filePath = "E:\\self_web\\git_dev\\vue\\zFei_springBoot\\target\\"; try { FileUtil.uploadFile(file.getBytes(), filePath, fileName); } catch (Exception e) { // TODO: 处理异常信息 } } // 上传文件2 @PostMapping("upload2") public void upload2(@RequestParam("file") MultipartFile uploadFile) { String fileName = uploadFile.getOriginalFilename(); String filePath = "E:\\self_web\\git_dev\\vue\\zFei_springBoot\\target\\"; try { FileUtil.uploadFile2(uploadFile.getInputStream(), filePath, fileName); } catch (Exception e) { // TODO: 处理异常信息 } } // 上传文件3 @PostMapping("upload3") public void upload3(@RequestParam("file") MultipartFile uploadFile) { String fileName = uploadFile.getOriginalFilename(); String filePath = "E:\\self_web\\git_dev\\vue\\zFei_springBoot\\target\\"; try { FileUtil.uploadFile3(uploadFile, filePath, fileName); } catch (Exception e) { // TODO: 处理异常信息 } } // 下载文件 @GetMapping("download") public void download() { } }
03) postman 测试
分类:
Spring Boot
标签:
Spring Boot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)