Business scenario: When the ssm framework uploads files to the application server, it needs to be transferred to the dedicated file server and return the url for other operations.
Business difficulty: MultipartFile to File type
Solution code:
/** * Convert MultipartFile to File * * @param multfile original file type * @return File * @throws IOException */ private File multipartToFile(MultipartFile multfile) throws IOException { CommonsMultipartFile cf = (CommonsMultipartFile)multfile; //This myfile is MultipartFile DiskFileItem fi = (DiskFileItem) cf.getFileItem(); File file = fi.getStoreLocation(); //Create a temporary file manually 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; }Note: If the upload file size is less than 2048, no temporary file will be generated
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8" /> <property name="maxUploadSize" value="10240000" /> <!-- Set the maximum value that is allowed to be written to memory during file upload, in bytes, the default is 10240 --> <!-- But after experiments, if the upload file size is smaller than this parameter, no temporary file will be generated, so it is changed to 2048 --> <property name="maxInMemorySize" value="2048" /> </bean>Solver : fage