CommonsMultipartFile和File的互相转换

一、 CommonsMultipartFile转为File(曲线救国)

此处用曲线救国的方式:先用CommonsMultipartFile的getInputStream()方法获取到一个InputStream类型的对象,再将InputStream类型转化为File

 //将InputStream类型转化为File类型
     private static void inputStreamToFile(InputStream ins, File file) {
      //将输出流转化为文件即可
      FileOutputStream os = null;
      try {
       os = new FileOutputStream(file);
       int bytesRead = 0;
       byte[] buffer = new byte[1024];
       while((bytesRead = ins.read(buffer)) != -1) {
        os.write(buffer, 0, bytesRead);
       }
      }catch(Exception e) {
       throw new RuntimeException("调用inputStreamToFile产生异常:"+e.getMessage());
      }finally {
       try {
        if(os != null) {
         os.close();
        }
        if(ins != null) {
         ins.close();
        }
       }catch(IOException e) {
        throw new RuntimeException("inputStreamToFile关闭io时产生异常:"+e.getMessage());
       }
      }
     }
  //使用inputStreamToFile方法
   //创建文件时,随便加一个空路径,将文件创建出来,后续再删除即可
   File xxFile = new File("一个不重复的路径");
   try {
    xxFile.createNewFile();
   } catch (IOException e) {
    //处理异常信息
   }
   try {
    inputStreamToFile(xxCommonsMultipartFile.getInputStream(), xxFile);
   } catch (IOException e) {
    //处理异常信息
   }
   //xxFile就是转化后的File文件

二、File转为CommonsMultipartFile

  //把File转化为CommonsMultipartFile
     public FileItem createFileItem(File file, String fieldName) {
      //DiskFileItemFactory():构造一个配置好的该类的实例
      //第一个参数threshold(阈值):以字节为单位.在该阈值之下的item会被存储在内存中,在该阈值之上的item会被当做文件存储
      //第二个参数data repository:将在其中创建文件的目录.用于配置在创建文件项目时,当文件项目大于临界值时使用的临时文件夹,默认采用系统默认的临时文件路径
      FileItemFactory factory = new DiskFileItemFactory(16, null);
      //fieldName:表单字段的名称;第二个参数 ContentType;第三个参数isFormField;第四个:文件名
      FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
      int bytesRead = 0;
      byte[] buffer = new byte[8192];
      FileInputStream fis = null;
      OutputStream os = null;
      try {
       fis = new FileInputStream(file);
       os = item.getOutputStream();
       while((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
        os.write(buffer, 0, bytesRead);//从buffer中得到数据进行写操作
       }
      } catch(IOException e) {
       e.printStackTrace();
      } finally {
       try {
        if(os != null) {
         os.close();
        }
        if(fis != null) {
         fis.close();
        }
       } catch (IOException e) {
        e.printStackTrace();
       }
      }
      return item;
     }
   //使用
    FileItem fileItem = createFileItem(xxFile, "表单字段名");
    CommonsMultipartFile xxCMF = new CommonsMultipartFile(fileItem);
    //xxCMF就是转化后的CommonsMultipartFile文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值