版权声明:本文为博主原创文章,转载请注明作者和出处,如有错误,望不吝赐教。 https://blog.csdn.net/weixin_41888813/article/details/83859448
图片上传功能的具体实现(当然文件也一样):
-
MultipartFile ,这个类可以完全接收到前台传过来的图片数据。
-
MultipartFile 通过 MultipartFile .transferTo( new File()), 仅需要这步骤,就可以把图片存到服务器所在的电脑的任意一个盘或者路径里面。
这里需要注意的一点:
- new File("d:/stair/secondLevel/test.png"),要创建这样有上级的 File文件时, 你要先判断test.png 的父级路径是否存在,如果不存在则要先创建。否则会报一个错误,“java.io.FileNotFoundException”
前端部分参详:
后端要点:
后端controller参数接收
@RequestParam(name = "files") MultipartFile[] files
MultipartFile接口源码
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.web.multipart;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.core.io.InputStreamSource;
import org.springframework.lang.Nullable;
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;
void transferTo(File var1) throws IOException, IllegalStateException;
}
在业务层,我们就可以通过自定义一个FileInfo实体类用于接收这些属性:
file.getContentType()
file.getOriginalFilename()
另一种将MultipartFile转File的方式:
MultipartFile file = xxx;
CommonsMultipartFile cf= (CommonsMultipartFile)file;
DiskFileItem fi = (DiskFileItem)cf.getFileItem();
File f = fi.getStoreLocation();
---------------------
不过还是建议用 transferTo(File dest)
参考来源: