文件转MultipartFile类型

        multipartfile是spring定义的一个接口在一些文件上传下载操作比如oss文件上传是需要这个类的,file是无法直接转换为multipartfile的。但是可以自己实现一个multipartfile具体类,在这个类中将file封装;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

public FileItem createFileItem(File file) {
    FileItemFactory factory = new DiskFileItemFactory(16, null);
    String textFieldName = "exportFile";
    FileItem item = factory.createItem(textFieldName, "multipart/form-data", false, file.getName());
    int bytesRead = 0;
    byte[] buffer = new byte[8192];
    try {
        FileInputStream fis = new FileInputStream(file);
        OutputStream os = item.getOutputStream();
        while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        fis.close();
    } catch (IOException e) {
        log.error("上传excel文件过程失败",e);
    }
    return item;
}

/**
 * 文件上传
 * 1.转为MultipartFile文件
 * 2.调用system上传文件服务上传到阿里云,接受返回的下载路径
 * 3.补充下载路径返回完整的可用的下载路径
 */
 {
File excelfile = new File(path);
MultipartFile mfile = new CommonsMultipartFile(createFileItem(excelfile));
ArrayList<String> urls = systemClientService.fileUpload(mfile);
FileUtils.delete(excelfile);
return Result.buildSuccess("导出成功", urls.get(0));
}

至于MultipartFile类型转为file只需要获得

multipartFile.getInputStream()

 中inputStream,在用其它工具写出来就行,这个很简单

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值