文件上传
通过MultipartFile或者MultipartFile[]接受文件
MultipartFile[]因为是数组如果包涵文件夹就需要遍历获取路径了
然后getOriginalFilename()方法获取文件名
String urlName = m.getOriginalFilename();
File infile = new File(path + urlName);//设置路径
if(!path.exists()){
path.mkdirs();
}
try {
m.transferTo(infile);//转存文件
} catch (IOException e) {
e.printStackTrace();
}
这样就把MultipartFile中的文件保存到了指定位置
File转MultipartFile格式有两种方法
// 1
File file = new File("D:/批量导入配件库模板 - 副本.xlsx");
FileInputStream in = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile(String newName,String oldName,String type,InputStream in);
// 2
File f = new File(path);
FileItem fileItem = new DiskFileItem("mainFile", Files.probeContentType(f.toPath()), false, f.getName(), (int) f.length(), f.getParentFile());
try (InputStream input = new FileInputStream(f); OutputStream os = fileItem.getOutputStream();) {
IOUtils.copy(input, os);
MultipartFile mulFile = new CommonsMultipartFile(fileItem);
}
MultipartFile是SpringMVC提供简化上传操作的工具类。
在不使用框架之前,都是使用原生的HttpServletRequest来接收上传的数据,文件是以二进制流传递到后端的,然后需要我们自己转换为File类。使用了MultipartFile工具类之后,我们对文件上传的操作就简便许多了。
getName();返回参数的名称
getOriginalFilename();获取源文件的昵称
getContentType(); 返回文件的内容类型
boolean isEmpty(); 判断是否为空,或者上传的文件是否有内容
long getSize() 返回文件大小 以字节为单位
byte[] getBytes() 将文件内容转化成一个byte[] 返回(throws IOException)
InputStream getInputStream() 返回InputStream读取文件的内容(throws IOException)
default Resource getResource() {
return new MultipartFileResource(this);
}
transferTo(File dest) 用来把 MultipartFile 转换换成 File(throws IOException, IllegalStateException)
void transferTo(File var1) throws IOException, IllegalStateException;
default void transferTo(Path dest) throws IOException, IllegalStateException {
FileCopyUtils.copy(this.getInputStream(), Files.newOutputStream(dest));
}
}
package org.springframework.core.io;
import java.io.IOException;
import java.io.InputStream;
//InputStreamSource 这个接口本质上返回的还是一个InputStream 流对象
public interface InputStreamSource {
//定位并打开资源,返回资源对应的输入流。
//每次调用都会返回新的输入流,调用者在使用完毕后必须关闭该资源。
InputStream getInputStream() throws IOException;
}