CommonsMultipartFile轉File

一般我們處理文件的時候都喜歡使用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();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章