package com.hx.util; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.io.IOUtils; import org.springframework.http.MediaType; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; import java.io.*; public class MultipartFileUtil { /**文件转化 * File to MultipartFile * @param file * @return */ public static MultipartFile getMultipartFile(File file) { FileItem item = new DiskFileItemFactory().createItem("file" , MediaType.MULTIPART_FORM_DATA_VALUE , true , file.getName()); try (InputStream input = new FileInputStream(file); OutputStream os = item.getOutputStream()) { // 流转移 IOUtils.copy(input, os); } catch (Exception e) { throw new IllegalArgumentException("Invalid file: " + e, e); } return new CommonsMultipartFile(item); } /**文件转化 * File to MultipartFile * @param file 文件 * @param fileName 带后缀的文件名 * @return */ public static MultipartFile getMultipartFileWithName(File file,String fileName) { FileItem item = new DiskFileItemFactory().createItem("file" , MediaType.MULTIPART_FORM_DATA_VALUE , true , StringUtils.isEmpty(fileName)?file.getName():fileName); try (InputStream input = new FileInputStream(file); OutputStream os = item.getOutputStream()) { // 流转移 IOUtils.copy(input, os); } catch (Exception e) { throw new IllegalArgumentException("Invalid file: " + e, e); } return new CommonsMultipartFile(item); } }