MultipartFile和File 的区别
MuitipartFile是Spring框架中用来处理文件上传的接口,它封装了文件上传的信息,比如文件名、文件类型等。
File是Java标准库中提供的文件操作类,用于描述文件信息,比如文件路径、文件大小等
总的来说,MultipantFile是用来处理文件上传的,而File则是用来描述文件信息的。
MultipartFile 与 File 的 互相转换
1. MultipartFile 转 File
最常见的方式(通过文件流写入):
public File multipartFile2File (MultipartFile multipartFile) {// 创建临时文件String path = "export/demo.xlsx";File file = new File(path);InputStream inputStream = null;FileOutputStream outputStream = null;try {// 获取文件输入流inputStream = multipartFile.getInputStream(); if (!file.exists()) {file.createNewFile();}// 创建输出流outputStream = new FileOutputStream(file);byte[] bytes = new byte[1024];int len;// 写入到创建的临时文件while ((len = inputStream.read(bytes)) > 0) {outputStream.write(bytes, 0, len);}} catch (Exception e) {throw new RuntimeException(e);} finally {// 关流try {if (outputStream != null) {outputStream.close();}if (outputStream != null) {inputStream.close();}outputStream.close();} catch (IOException e) {throw new RuntimeException(e);}}return file;}
最简单的方式:
使用Spring中的FileCpopyUtils类的copy()方法将MultipartFile 转换为File类型
public File multipartFile2File (MultipartFile multipartFile) {String path = "export/demo.xlsx";File file = new File(path);try {if (!file.exists()) {file.createNewFile();}// 底层也是通过io流写入文件fileFileCopyUtils.copy(multipartFile.getBytes(), file);} catch (Exception e) {throw new RuntimeException(e);}return file;}
2. File 转 MultipartFile
使用org.springframework.mock.web.MockMultipartFile 需要导入spring-test.jar
public MultipartFile file2MultipartFile () {String path = "export/demo.xlsx";File file = new File(path);MultipartFile multipartFile;try {FileInputStream fileInputStream = new FileInputStream(file);multipartFile = new MockMultipartFile("copy"+file.getName(),file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(),fileInputStream);System.out.println(multipartFile.getName()); // 输出demo.xlsxfileInputStream.close();} catch (Exception e) {throw new RuntimeException(e);}return multipartFile;}
使用CommonsMultipartFile
public MultipartFile file2MultipartFile () {String path = "export/demo.xlsx";File file = new File(path);MultipartFile multipartFile;try {DiskFileItem fileItem2 = (DiskFileItem) new DiskFileItemFactory().createItem("file", ContentType.MULTIPART.getValue(), true, file.getName());//也可以用IOUtils.copy(inputStream,os);Files.copy(Paths.get(file.getAbsolutePath()), fileItem2.getOutputStream());multipartFile = new CommonsMultipartFile(fileItem2);} catch (Exception e) {throw new RuntimeException(e);}return multipartFile;}
又是摸鱼的一天,,,,,