SpringBoot接收MultipartFile文件,并保存文件
package com.hrw.controller; import com.hrw.pojo.Result; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.*; /** * projectName: testSpring * * @author: xxx * time: 2022/7/17 16:12 * description: */ @RestController @RequestMapping("/test") public class TestController { @PostMapping("/aaa") public Result test1(MultipartFile file111, HttpServletRequest request) { String fileName = file111.getOriginalFilename(); System.out.println("完整文件名 = " + fileName); InputStream inputStream = null; FileOutputStream fileOut = null; try { inputStream = file111.getInputStream(); fileOut = new FileOutputStream(fileName);//这里可以改路径 IOUtils.copy(inputStream, fileOut); fileOut.flush(); } catch (IOException e) { e.printStackTrace(); }finally { try { if (inputStream != null) { inputStream.close(); } if (fileOut != null) { fileOut.close(); } } catch (IOException e) { e.printStackTrace(); } } return new Result(200,"成功了"); } }
记得修改配置文件,不然文件超过限制可能传不了,(下面配置方式仅供参考,不同版本可能会有所不同)
server:
port: 8018
spring:
application:
name: testSpring
servlet.multipart.enabled: true
servlet.multipart.max-file-size: 100MB
servlet.multipart.max-request-size: 1000MB
测试的方法是在postman里面,from里放一个File类型的参数,如下图所示