SpringMVC上传文件的MultipartFile源码

0.MultipartFile上传文件的具体实例如下:

http://blog.csdn.net/swingpyzf/article/details/20230865

1.MultipartFile接口源码如下:

public interface MultipartFile {
    String getName();
    //获取文件原名(不包含路径)
    String getOriginalFilename();
    //获取上传文件的类型
    String getContentType();

    boolean isEmpty();

    long getSize();

    byte[] getBytes() throws IOException;

    InputStream getInputStream() throws IOException;
    //保存到一个目标文件中
    void transferTo(File var1) throws IOException, IllegalStateException;
}

2.MultipartFile接口的实现类CommonsMultipartFile源码如下:

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 ex = "transferred";
                    if(!this.fileItem.isInMemory()) {
                        ex = this.isAvailable()?"copied":"moved";
                    }

                    logger.debug("Multipart file \‘" + this.getName() + "\‘ with original filename [" + this.getOriginalFilename() + "], stored " + this.getStorageDescription() + ": " + ex + " 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() {
        return this.fileItem.isInMemory()?true:(this.fileItem instanceof DiskFileItem?((DiskFileItem)this.fileItem).getStoreLocation().exists():this.fileItem.getSize() == this.size);
    }

    public String getStorageDescription() {
        return this.fileItem.isInMemory()?"in memory":(this.fileItem instanceof DiskFileItem?"at [" + ((DiskFileItem)this.fileItem).getStoreLocation().getAbsolutePath() + "]":"on disk");
    }
}

3.FileItem接口,具体的api介绍如以下链接:

http://www.jb51.net/article/90331.htm

4.FileItem的实现类DiskFileItem源码如下:

public class DiskFileItem implements FileItem {
    private static final long serialVersionUID = 2237570099615271025L;
    public static final String DEFAULT_CHARSET = "ISO-8859-1";
    private static final String UID = UUID.randomUUID().toString().replace(‘-‘, ‘_‘);
    private static final AtomicInteger COUNTER = new AtomicInteger(0);
    private String fieldName;
    private final String contentType;
    private boolean isFormField;
    private final String fileName;
    private long size = -1L;
    private final int sizeThreshold;
    private final File repository;
    private byte[] cachedContent;
    private transient DeferredFileOutputStream dfos;
    private transient File tempFile;
    private File dfosFile;
    private FileItemHeaders headers;

    public DiskFileItem(String fieldName, String contentType, boolean isFormField, String fileName, int sizeThreshold, File repository) {
        this.fieldName = fieldName;
        this.contentType = contentType;
        this.isFormField = isFormField;
        this.fileName = fileName;
        this.sizeThreshold = sizeThreshold;
        this.repository = repository;
    }

    public InputStream getInputStream() throws IOException {
        if(!this.isInMemory()) {
            return new FileInputStream(this.dfos.getFile());
        } else {
            if(this.cachedContent == null) {
                this.cachedContent = this.dfos.getData();
            }

            return new ByteArrayInputStream(this.cachedContent);
        }
    }

    public String getContentType() {
        return this.contentType;
    }

    public String getCharSet() {
        ParameterParser parser = new ParameterParser();
        parser.setLowerCaseNames(true);
        Map params = parser.parse(this.getContentType(), ‘;‘);
        return (String)params.get("charset");
    }

    public String getName() {
        return Streams.checkFileName(this.fileName);
    }

    public boolean isInMemory() {
        return this.cachedContent != null?true:this.dfos.isInMemory();
    }

    public long getSize() {
        return this.size >= 0L?this.size:(this.cachedContent != null?(long)this.cachedContent.length:(this.dfos.isInMemory()?(long)this.dfos.getData().length:this.dfos.getFile().length()));
    }

    public byte[] get() {
        if(this.isInMemory()) {
            if(this.cachedContent == null) {
                this.cachedContent = this.dfos.getData();
            }

            return this.cachedContent;
        } else {
            byte[] fileData = new byte[(int)this.getSize()];
            BufferedInputStream fis = null;

            try {
                fis = new BufferedInputStream(new FileInputStream(this.dfos.getFile()));
                fis.read(fileData);
            } catch (IOException var12) {
                fileData = null;
            } finally {
                if(fis != null) {
                    try {
                        fis.close();
                    } catch (IOException var11) {
                        ;
                    }
                }

            }

            return fileData;
        }
    }

    public String getString(String charset) throws UnsupportedEncodingException {
        return new String(this.get(), charset);
    }

    public String getString() {
        byte[] rawdata = this.get();
        String charset = this.getCharSet();
        if(charset == null) {
            charset = "ISO-8859-1";
        }

        try {
            return new String(rawdata, charset);
        } catch (UnsupportedEncodingException var4) {
            return new String(rawdata);
        }
    }

    public void write(File file) throws Exception {
        if(this.isInMemory()) {
            FileOutputStream outputFile = null;

            try {
                outputFile = new FileOutputStream(file);
                outputFile.write(this.get());
            } finally {
                if(outputFile != null) {
                    outputFile.close();
                }

            }
        } else {
            File outputFile1 = this.getStoreLocation();
            if(outputFile1 == null) {
                throw new FileUploadException("Cannot write uploaded file to disk!");
            }

            this.size = outputFile1.length();
            if(!outputFile1.renameTo(file)) {
                BufferedInputStream in = null;
                BufferedOutputStream out = null;

                try {
                    in = new BufferedInputStream(new FileInputStream(outputFile1));
                    out = new BufferedOutputStream(new FileOutputStream(file));
                    IOUtils.copy(in, out);
                } finally {
                    if(in != null) {
                        try {
                            in.close();
                        } catch (IOException var19) {
                            ;
                        }
                    }

                    if(out != null) {
                        try {
                            out.close();
                        } catch (IOException var18) {
                            ;
                        }
                    }

                }
            }
        }

    }

    public void delete() {
        this.cachedContent = null;
        File outputFile = this.getStoreLocation();
        if(outputFile != null && outputFile.exists()) {
            outputFile.delete();
        }

    }

    public String getFieldName() {
        return this.fieldName;
    }

    public void setFieldName(String fieldName) {
        this.fieldName = fieldName;
    }

    public boolean isFormField() {
        return this.isFormField;
    }

    public void setFormField(boolean state) {
        this.isFormField = state;
    }

    public OutputStream getOutputStream() throws IOException {
        if(this.dfos == null) {
            File outputFile = this.getTempFile();
            this.dfos = new DeferredFileOutputStream(this.sizeThreshold, outputFile);
        }

        return this.dfos;
    }

    public File getStoreLocation() {
        return this.dfos == null?null:this.dfos.getFile();
    }

    protected void finalize() {
        File outputFile = this.dfos.getFile();
        if(outputFile != null && outputFile.exists()) {
            outputFile.delete();
        }

    }

    protected File getTempFile() {
        if(this.tempFile == null) {
            File tempDir = this.repository;
            if(tempDir == null) {
                tempDir = new File(System.getProperty("java.io.tmpdir"));
            }

            String tempFileName = String.format("upload_%s_%s.tmp", new Object[]{UID, getUniqueId()});
            this.tempFile = new File(tempDir, tempFileName);
        }

        return this.tempFile;
    }

    private static String getUniqueId() {
        int limit = 100000000;
        int current = COUNTER.getAndIncrement();
        String id = Integer.toString(current);
        if(current < 100000000) {
            id = ("00000000" + id).substring(id.length());
        }

        return id;
    }

    public String toString() {
        return String.format("name=%s, StoreLocation=%s, size=%s bytes, isFormField=%s, FieldName=%s", new Object[]{this.getName(), this.getStoreLocation(), Long.valueOf(this.getSize()), Boolean.valueOf(this.isFormField()), this.getFieldName()});
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
        if(this.dfos.isInMemory()) {
            this.cachedContent = this.get();
        } else {
            this.cachedContent = null;
            this.dfosFile = this.dfos.getFile();
        }

        out.defaultWriteObject();
    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();
        if(this.repository != null) {
            if(!this.repository.isDirectory()) {
                throw new IOException(String.format("The repository [%s] is not a directory", new Object[]{this.repository.getAbsolutePath()}));
            }

            if(this.repository.getPath().contains("\u0000")) {
                throw new IOException(String.format("The repository [%s] contains a null character", new Object[]{this.repository.getPath()}));
            }
        }

        OutputStream output = this.getOutputStream();
        if(this.cachedContent != null) {
            output.write(this.cachedContent);
        } else {
            FileInputStream input = new FileInputStream(this.dfosFile);
            IOUtils.copy(input, output);
            this.dfosFile.delete();
            this.dfosFile = null;
        }

        output.close();
        this.cachedContent = null;
    }

    public FileItemHeaders getHeaders() {
        return this.headers;
    }

    public void setHeaders(FileItemHeaders pHeaders) {
        this.headers = pHeaders;
    }
}
时间: 2024-10-21 22:53:09

SpringMVC上传文件的MultipartFile源码的相关文章

Spring MVC 4 使用常规的fileupload上传文件(带源码)

[本系列其他教程正在陆续翻译中,点击分类:spring 4 mvc 进行查看.源码下载地址在文章末尾.] [翻译 by 明明如月 QQ 605283073] 上一篇: Spring MVC 4 文件上传下载 Hibernate+MySQL例子 (带源码) 原文地址:http://websystique.com/springmvc/spring-mvc-4-file-upload-example-using-commons-fileupload/ 本文将实现使用SpringMultipartRes

SpringMVC上传文件的三种解析方式

springMVC上传文件后,在action解析file文件的三种方式. jsp页面的写法: <form action="parserUploadFile1" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit"

springmvc上传文件,抄别人的

SpringMVC中的文件上传 分类: SpringMVC 2012-05-17 12:55 26426人阅读 评论(13) 收藏 举报 stringuserinputclassencoding 这是用的是SpringMVC-3.1.1.commons-fileupload-1.2.2和io-2.0.1 首先是web.xml [html] view plaincopyprint? <?xml version="1.0" encoding="UTF-8"?>

2. SpringMVC 上传文件操作

1.创建java web项目:SpringMVCUploadDownFile 2.在项目的WebRoot下的WEB-INF的lib包下添加如下jar文件 1 com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar 2 com.springsource.net.sf.cglib-2.2.0.jar 3 com.springsource.org.aopalliance-1.0.0.jar 4 com.springsource.org.apache.commo

SpringMVC上传文件总结

如果是maven项目 需要在pom.xml文件里面引入下面两个jar包 <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>com

springmvc 上传文件的问题

今天用springmvc 上传文件的时候 报错 org.apache.catalina.connector.RequestFacade cannot be cast to org.springframework.web.multipart.MultipartHttpServletRequest 网上查找原因 说的有如下几种: 1.表单form 上没有 enctype="multipart/form-data"   这个属性 2.配置文件: <bean id="multi

springmvc 上传文件时的错误

使用springmvc上传文件一直失败,文件参数一直为null, 原来是配置文件没写成功. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 最大上传尺寸 B单位 1M= 1024*1024 --> <property name="maxUploadSize&

SpringMVC上传文件(图片)并保存到本地

SpringMVC上传文件(图片)并保存到本地 小记一波~ 基本的MVC配置就不展示了,这里给出核心代码 在spring-mvc的配置文件中写入如下配置 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize">

SpringMVC上传文件的三种方式(转载)

直接上代码吧,大伙一看便知 这时:commonsmultipartresolver 的源码,可以研究一下 http://www.verysource.com/code/2337329_1/commonsmultipartresolver.java.html 前台: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 <%@ page language="java" contentTy