springmvc 中將MultipartFile轉為file,springboot 注入CommonsMultipartResolver
阿新 • • 發佈:2018-11-05
第一種方法: 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; }