读取本地文件转化成MultipartFile

本文介绍如何使用Spring框架的MultipartFile实现将大量文件上传到阿里云OSS。通过ExecutorService并行处理,展示了如何创建MockMultipartFile,处理文件流,并处理上传过程中的异常。

介绍

现在有个上传文件功能,需要将文件上传到oss上,但是文件有点多,于是使用接口进行上传。但是需要上传文件转换为MultipartFile类型文件进行上传。

上传文件代码

 @RequestMapping(value = "up")
    public String upFile() {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
        String filepath = "D:\\work\\files";//D盘下的file文件夹的目录
        File file = new File(filepath);//File类型可以是文件也可以是文件夹
        File[] fileList = file.listFiles();//将该目录下的所有文件放置在一个File类型的数组中
        for (int j = 0; j < fileList.length; j++) {
            final int i = j;
            fixedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        File pdf = fileList[i];
                        FileInputStream fileInputStream = null;
                        fileInputStream = new FileInputStream(pdf);
                        MultipartFile multipartFile = new MockMultipartFile(pdf.getName(), pdf.getName(),
                                ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
                        String url = ossFileUtils.upload(multipartFile.getOriginalFilename(), multipartFile);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                }
            });

        }
        return "成功";
    }

 核心代码块

import java.io.File;
import java.io.FileInputStream;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.mock.web.MockMultipartFile;
import org.apache.http.entity.ContentType;
 
 
File pdfFile = new File("D://test.pdf");
FileInputStream fileInputStream = new FileInputStream(pdfFile);
MultipartFile multipartFile = new MockMultipartFile(pdfFile.getName(), pdfFile.getName(),
					ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);

参考:

https://www.cnblogs.com/zhenghengbin/p/11096860.html 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值