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