一般我们处理文件的时候都喜欢使用Java中的File.io类。今天首次遇到了一个CommonsMultipartFile的类。
具体代码如下,下面是一个实现文件上传的一个接口。
public String upload(@RequestParam("file")CommonsMultipartFile partFile, HttpServletRequest request) throws IOException {
try{
String path = request.getServletContext().getRealPath("/upload");
System.out.println(path);
String name = request.getParameter("name");
System.out.println(name);
log.info(name);
log.info("upload---------------start---------------------");
log.info(path);
String filename = partFile.getOriginalFilename();
File file = new File(path+"/"+filename);
InputStream inputStream = partFile.getInputStream();
FileUtils.copyInputStreamToFile(inputStream, file);
if(inputStream!=null) {
inputStream.close();
}
return "文件上传成功!";
}catch (Exception e){
e.printStackTrace();
return "文件上传失败!";
}
}
通过查看源码,仿佛一切很容易理解
public class CommonsMultipartFile implements MultipartFile, Serializable {
protected static final Log logger = LogFactory.getLog(CommonsMultipartFile.class);
private final FileItem fileItem;
private final long size;
public CommonsMultipartFile(FileItem fileItem) {
this.fileItem = fileItem;
this.size = this.fileItem.getSize();
}
public final FileItem getFileItem() {
return this.fileItem;
}
public String getName() {
return this.fileItem.getFieldName();
}
public String getOriginalFilename() {
String filename = this.fileItem.getName();
if (filename == null) {
return "";
} else {
int pos = filename.lastIndexOf("/");
if (pos == -1) {
pos = filename.lastIndexOf("\\");
}
return pos != -1 ? filename.substring(pos + 1) : filename;
}
}
public String getContentType() {
return this.fileItem.getContentType();
}
public boolean isEmpty() {
return this.size == 0L;
}
public long getSize() {
return this.size;
}
public byte[] getBytes() {
if (!this.isAvailable()) {
throw new IllegalStateException("File has been moved - cannot be read again");
} else {
byte[] bytes = this.fileItem.get();
return bytes != null ? bytes : new byte[0];
}
}
public InputStream getInputStream() throws IOException {
if (!this.isAvailable()) {
throw new IllegalStateException("File has been moved - cannot be read again");
} else {
InputStream inputStream = this.fileItem.getInputStream();
return (InputStream)(inputStream != null ? inputStream : new ByteArrayInputStream(new byte[0]));
}
}
public void transferTo(File dest) throws IOException, IllegalStateException {
if (!this.isAvailable()) {
throw new IllegalStateException("File has already been moved - cannot be transferred again");
} else if (dest.exists() && !dest.delete()) {
throw new IOException("Destination file [" + dest.getAbsolutePath() + "] already exists and could not be deleted");
} else {
try {
this.fileItem.write(dest);
if (logger.isDebugEnabled()) {
String action = "transferred";
if (!this.fileItem.isInMemory()) {
action = this.isAvailable() ? "copied" : "moved";
}
logger.debug("Multipart file '" + this.getName() + "' with original filename [" + this.getOriginalFilename() + "], stored " + this.getStorageDescription() + ": " + action + " to [" + dest.getAbsolutePath() + "]");
}
} catch (FileUploadException var3) {
throw new IllegalStateException(var3.getMessage());
} catch (IOException var4) {
throw var4;
} catch (Exception var5) {
logger.error("Could not transfer to file", var5);
throw new IOException("Could not transfer to file: " + var5.getMessage());
}
}
}
protected boolean isAvailable() {
if (this.fileItem.isInMemory()) {
return true;
} else if (this.fileItem instanceof DiskFileItem) {
return ((DiskFileItem)this.fileItem).getStoreLocation().exists();
} else {
return this.fileItem.getSize() == this.size;
}
}
public String getStorageDescription() {
if (this.fileItem.isInMemory()) {
return "in memory";
} else {
return this.fileItem instanceof DiskFileItem ? "at [" + ((DiskFileItem)this.fileItem).getStoreLocation().getAbsolutePath() + "]" : "on disk";
}
}
}
MultipartFile是spring中定义的一个接口,file是无法转换为multipartfile的。但是可以定义一个具体类,并实现MultipartFile,用具体类将file进行封装,将file封装为MultipartFile。
如果系统中有spring-test jar包,则可以直接使用MockMultipartFile。
在网上找了个靠谱一些的代码,丰富一下自己的代码库吧。
public void getFile(@RequestParam("cmfFile") CommonsMultipartFile cmfFile) {
CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile)cmfFile;
DiskFileItem diskFileItem = (DiskFileItem)commonsMultipartFile.getFileItem();
File file = diskFileItem.getStoreLocation();
}