首页 > 技术文章 > Springmvc 上传文件MultipartFile 转File

tv151579 2017-09-18 23:57 原文

转自:http://blog.csdn.net/boneix/article/details/51303207

业务场景:ssm框架 上传文件到应用服务器过程中要传到专有的文件服务器并返回url进行其他操作。

业务难点:MultipartFile转File类型

解决代码:

    /** 
     * MultipartFile 转换成File 
     *  
     * @param multfile 原文件类型 
     * @return File 
     * @throws IOException 
     */  
    private File multipartToFile(MultipartFile multfile) throws IOException {  
        CommonsMultipartFile cf = (CommonsMultipartFile)multfile;   
        //这个myfile是MultipartFile的  
        DiskFileItem fi = (DiskFileItem) cf.getFileItem();  
        File file = fi.getStoreLocation();  
        //手动创建临时文件  
        if(file.length() < CommonConstants.MIN_FILE_SIZE){  
            File tmpFile = new File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") +   
                    file.getName());  
            multfile.transferTo(tmpFile);  
            return tmpFile;  
        }  
        return file;  
    }

注意事项:上传文件大小若小于2048,则不会生成临时文件

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="defaultEncoding" value="UTF-8" />  
        <property name="maxUploadSize" value="10240000" />  
        <!-- 设置在文件上传时允许写到内存中的最大值,以字节为单位计算,默认是10240 -->  
        <!-- 但是经实验,上传文件大小若小于此参数,则不会生成临时文件,故改为2048 -->  
        <property name="maxInMemorySize" value="2048" />    
</bean>

 

推荐阅读