思路:把MultipartFile先存到项目目录下(或者磁盘),存的时候修改文件名,再读取出来转成MultipartFile
1.实现代码:MultipartFile先存到项目目录,再读取出来File
public static MultipartFile newFileName ( MultipartFile multipartFile, String env) { String path = ClassLoader . getSystemResource ( "" ) . getPath ( ) . concat ( "new_file" ) ; if ( ! "loc" . equals ( env) ) { path = System . getProperty ( "user.dir" ) + "/BOOT-INF/classes/new_file/" ; } log. info ( "新文件存储路径:{}" , path) ; try { String ext = FileUtil . extName ( multipartFile. getOriginalFilename ( ) ) ; String fileName = StringHelper . getUUID ( 16 ) . concat ( "." ) . concat ( ext) ; File file = new File ( path, fileName) ; File parentFile = file. getParentFile ( ) ; if ( ! parentFile. exists ( ) ) { parentFile. mkdir ( ) ; } multipartFile. transferTo ( file) ; if ( ! file. exists ( ) ) { return null ; } MultipartFile mf = FileHelper . file2MultipartFile ( file) ; boolean delete = file. delete ( ) ; log. info ( "合成海报临时文件删除:{}" , delete) ; return mf; } catch ( IOException e) { log. error ( e. getLocalizedMessage ( ) ) ; } return null ;
}
2.实现代码:把File转MultipartFile
import org. apache. commons. fileupload. FileItem ;
import org. apache. commons. fileupload. disk. DiskFileItemFactory ;
import org. springframework. web. multipart. MultipartFile ;
import org. springframework. web. multipart. commons. CommonsMultipartFile ; import java. io. File ;
import java. io. FileInputStream ;
import java. io. IOException ;
import java. io. OutputStream ; public static MultipartFile file2MultipartFile ( File file) { return new CommonsMultipartFile ( createFileItem ( file) ) ;
} private static FileItem createFileItem ( File file) { DiskFileItemFactory factory = new DiskFileItemFactory ( 16 , null ) ; FileItem fileItem = factory. createItem ( "testField" , "text/plain" , true , file. getName ( ) ) ; int byteRead = 0 ; byte [ ] buffer = new byte [ 8192 ] ; try ( FileInputStream fis = new FileInputStream ( file) ; OutputStream os = fileItem. getOutputStream ( ) ) { while ( ( byteRead = fis. read ( buffer, 0 , 8192 ) ) != - 1 ) { os. write ( buffer, 0 , byteRead) ; } os. close ( ) ; fis. close ( ) ; } catch ( IOException e) { log. error ( e. getLocalizedMessage ( ) ) ; } return fileItem;
}