MultipartFile
MultipartFile为org.springframework.web.mutipart包下的一个类;继承了InputStreamSource接口
如果想在项目中使用MultipartFile这个类,那么项目必须要使用spring框架才可以,否则无法引入这个类。
作用:主要是来实现以表单的形式进行文件上传
名称 | 作用 |
---|---|
String getName() | 返回参数的名称 |
String getOriginalFilename() | 获取源文件的昵称 |
getContentType() | 返回文件的内容类型 |
boolean isEmpty() | 判断是否为空,或者上传的文件是否有内容 |
long getSize() | 返回文件大小 以字节为单位 |
byte[] getBytes() | 将文件内容转化成一个byte[] 返回 |
InputStream getInputStream() | 返回InputStream读取文件的内容 |
void transferTo(File var1) | 复制文件传输给指定位置的文件var1 |
default void transferTo(Path dest) | 复制文件传输给指定路径dest下的文件中 |
源码分析:
/**
* InputStreamSource本质上返回的是一个InputStream流对象
* 定位并打开资源,返回资源对应的输入流。每次调用都会返回新的输入流,调用者在使用完毕后必须关闭该资源。
*/
public interface MultipartFile extends InputStreamSource {
String getName();
@Nullable
String getOriginalFilename();
@Nullable
String getContentType();
boolean isEmpty();
long getSize();
byte[] getBytes() throws IOException;
InputStream getInputStream() throws IOException;
default Resource getResource() {
return new MultipartFileResource(this);
}
void transferTo(File var1) throws IOException, IllegalStateException;
default void transferTo(Path dest) throws IOException, IllegalStateException {
FileCopyUtils.copy(this.getInputStream(), Files.newOutputStream(dest));
}
}
文件上传大小限制
上传的file文件超过了spring默认配置的最大值1048576 bytes,就会出现下边错误提示,因此我们在接收前端传递的文件时,需要在yml中修改配置参数的大小
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes.
SpringBoot不同的版本,对应的设置参数不同:
Spring Boot 1.3.x and earlier
- multipart.maxFileSize
- multipart.maxRequestSize
Spring Boot 1.4.x and 1.5.x
- spring.http.multipart.maxFileSize
- spring.http.multipart.maxRequestSize
Spring Boot 2.x
- spring.servlet.multipart.maxFileSize
- spring.servlet.multipart.maxRequestSize
在yml中设置单个文件最大请求10MB,最多一次请求10个文件
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=100MB
实例
MultipartFile file:是前端上传的文件
@PostMapping("/multipartFile")
@ApiOperation("上传文件")
public void uploadImg(@RequestParam("file")MultipartFile file){
String name = file.getOriginalFilename();//获取文件的名字
String base = "D:/emos/image/"+name;//要上传到本地的地址
File file1 = new File(base);//创建一个file对象
try {
file.transferTo(file1);//将前端上传的MultipartFile对象复制到file1中
System.out.println(file1.getAbsoluteFile());//获取文件的绝对路径
System.out.println(file1.getPath());//获取文件的相对路径
log.info("上传成功!");
} catch (IOException e) {
log.error("上传失败",e);
}
}