1 package cn.com.aia.grouplife.utils; 2 3 import org.apache.commons.fileupload.FileItem; 4 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 5 import org.springframework.util.FileCopyUtils; 6 import org.springframework.web.multipart.MultipartFile; 7 import org.springframework.web.multipart.commons.CommonsMultipartFile; 8 9 import javax.activation.MimetypesFileTypeMap; 10 import java.io.ByteArrayInputStream; 11 import java.io.File; 12 import java.io.InputStream; 13 import java.io.OutputStream; 14 15 public class FileToMultipartFileUtil { 16 17 18 public static MultipartFile toMultipartFile(String fieldName, File file) throws Exception { 19 DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); 20 String contentType = new MimetypesFileTypeMap().getContentType(file); 21 FileItem fileItem = diskFileItemFactory.createItem(fieldName, contentType, false, file.getName()); 22 try ( 23 InputStream inputStream = new ByteArrayInputStream(FileCopyUtils.copyToByteArray(file)); 24 OutputStream outputStream = fileItem.getOutputStream() 25 ) { 26 FileCopyUtils.copy(inputStream, outputStream); 27 } catch (Exception e) { 28 throw e; 29 } 30 MultipartFile multipartFile = new CommonsMultipartFile(fileItem); 31 return multipartFile; 32 } 33 34 35 public static MultipartFile toMultipartFile(String fieldName, String fileName, byte[] fileByteArray) throws Exception { 36 DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); 37 String contentType = new MimetypesFileTypeMap().getContentType(fileName); 38 FileItem fileItem = diskFileItemFactory.createItem(fieldName, contentType, false, fileName); 39 try ( 40 InputStream inputStream = new ByteArrayInputStream(fileByteArray); 41 OutputStream outputStream = fileItem.getOutputStream() 42 ) { 43 FileCopyUtils.copy(inputStream, outputStream); 44 } catch (Exception e) { 45 throw e; 46 } 47 MultipartFile multipartFile = new CommonsMultipartFile(fileItem); 48 return multipartFile; 49 } 50 51 }