1. 程式人生 > >springmvc 中將MultipartFile轉為file,springboot 注入CommonsMultipartResolver

springmvc 中將MultipartFile轉為file,springboot 注入CommonsMultipartResolver

第一種方法:

     MultipartFile file = xxx; 
        CommonsMultipartFile cf= (CommonsMultipartFile)file; 
        DiskFileItem fi = (DiskFileItem)cf.getFileItem(); 

        File f = fi.getStoreLocation();

  會在專案的根目錄的臨時資料夾下生成一個檔案;

第二種方法:

    transferTo(File dest);

  會在專案中生成一個新檔案;

第三種方法:   

  File f = (File) xxx 強轉即可。前提是要配置multipartResolver,要不然會報型別轉換失敗的異常。

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="104857600"/>
        <property name="maxInMemorySize" value="4096"/>
    </bean>
  沒試過;
第四種方法:
  Workbook wb = Workbook.getWorkbook(xxx .getInputStream());
  轉換為輸入流,直接讀取;
第五種方法:
  byte[] buffer = myfile.getBytes();
  先轉換為位元組陣列,沒試過;

複製程式碼

 

複製程式碼

 //顯示宣告CommonsMultipartResolver為mutipartResolver
    @Bean(name = "multipartResolver")
       public MultipartResolver multipartResolver(){
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        resolver.setDefaultEncoding("UTF-8");
        resolver.setResolveLazily(true);//resolveLazily屬性啟用是為了推遲檔案解析,以在在UploadAction中捕獲檔案大小異常
        resolver.setMaxInMemorySize(40960);
        resolver.setMaxUploadSize(50*1024*1024);//上傳檔案大小 50M 50*1024*1024
        return resolver;
    }   

複製程式碼

 

轉載於:https://www.cnblogs.com/huzi007/p/5971197.html