Springmvc 上傳文件MultipartFile 轉File


轉自: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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM