Java操作Zip文件、inputstream转为multipartfile

一、CommonsMultipartFile


    commons-fileupload
    commons-fileupload
    1.3.3

@Test
public void testOSSServiceImport(){
    File file = new File("test.png");
    DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",
            MediaType.ALL_VALUE, true, file.getName());

    try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) {
        IOUtils.copy(input, os);
    } catch (Exception e) {
        throw new IllegalArgumentException("Invalid file: " + e, e);
    }

    MultipartFile multi = new CommonsMultipartFile(fileItem);

}

二、mockFile

  • pom引入spring-test
    spring-boot-starter-test中包含spring-test相关依赖



    org.springframework.boot
    spring-boot-starter-test

import org.springframework.mock.web.MockMultipartFile;

MultipartFile file = new MockMultipartFile(name,name, MediaType.MULTIPART_FORM_DATA_VALUE, inputStream);

三、从网络url中操作zipFile

  • 网络text文件为pdf和流水号的映射
20211013_7935015_001_15000001903734_1634117754785_0.pdf 8043432110131215777753
20211013_7935016_008_15000001903734_1634117754402_0.pdf 8043432110131215777753
  • zip中的pdf文件


    zip中的pdf文件

步骤:

  • 1、从网络text文件中获取pdf和流水号的映射,存入到HashMap中。

  • 2、从对应的流水号中取出对应的pdf文件名。

  • 3、通过pdf文件名从Zip文件中取出pdf文件,并包装成MultipartFile,用于文件上传到文件服务器。

  • 引入commons-io或commons-fileupload 的maven依赖


    commons-io
    commons-io
    2.11.0



    commons-fileupload
    commons-fileupload
    1.4

  • ZipFileUtils 工具类
public class ZipFileUtils {

    private static final Logger logger = LoggerFactory.getLogger(ZipFileUtils.class);

    /**
     * 获取网络文件流
     * @param urlStr 网络文件url
     * @return 返回输入流
     * @throws IOException IO异常
     */
    private static InputStream downLoadFromUrl(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3*1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //得到输入流
        return conn.getInputStream();
    }

    /**
     * 获取网络文件流中的内容,一次读一行,并将空格拆开,返回
     * @param urlStr 网络文件url
     * @return 返回pdf文件名和银行流水号映射集合
     * @throws IOException IO异常
     */
    public static Map> downLoadFileContentFromUrl(String urlStr) throws IOException {
        Map> resultMap = new HashMap<>();
        InputStream inputStream = null;
        BufferedReader br = null;
        try {
            //得到输入流
            inputStream = downLoadFromUrl(urlStr);
            //构造一个BufferedReader类来读取文件
            br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String line = null;
            //使用readLine方法,一次读一行
            while ((line = br.readLine()) != null) {
                //通过空格进行切分
                String[] split = line.split(" ");
                if(split.length >= 2){
                    List pdfNameList = resultMap.get(split[1]);
                    if(CollectionUtils.isEmpty(pdfNameList)){
                        pdfNameList = new ArrayList<>();
                        pdfNameList.add(split[0]);
                        resultMap.put(split[1],pdfNameList);
                    }else{
                        pdfNameList.add(split[0]);
                    }
                }
            }
        } finally {
            //关闭流
            if(br != null){
                br.close();
            }
            if(inputStream != null){
                inputStream.close();
            }
        }
        return resultMap;
    }

    /**
     * 根据pdfName名称,从网络中获取Zip中的pdf文件InputStream
     * @param urlStr Zip文件的下载url
     * @param pdfName pdf名称
     * @return 返回输入流
     * @throws IOException IO异常
     */
    public static InputStream downLoadZipFileFromUrl(String urlStr,String pdfName) throws IOException {
        //声明字节输出数组
        ByteArrayOutputStream byteOut = null;
        ZipInputStream zipIn = null;
        InputStream inputStream = null;
        try {
            //得到输入流
            zipIn = new ZipInputStream(downLoadFromUrl(urlStr));
            ZipEntry entry = null;
            while ((entry = zipIn.getNextEntry()) != null) {
                if(pdfName.equals(entry.getName())) {
                    //初始化字节输出数组
                    byteOut = new ByteArrayOutputStream();
                    IOUtils.copy(zipIn, byteOut);
                    inputStream = new ByteArrayInputStream(byteOut.toByteArray());
                }
            }
            return inputStream;
        } finally {
            //关闭流
            if(byteOut != null){
                byteOut.close();
            }
            if(zipIn != null){
                zipIn.close();
            }
        }
    }

    /**
     * 根据pdfName名称,从网络中获取Zip中的pdf文件的MultipartFile
     * @param urlStr Zip文件的下载url
     * @param pdfName Zip文件的下载url
     * @return MultipartFile
     * @throws IOException IO异常
     */
    public static MultipartFile getMultipartFileFromUrl(String urlStr, String pdfName) throws IOException {
        String fileName = "Xxx文件.pdf";
        MultipartFile multipartFile = null;
        InputStream inputStream = downLoadZipFileFromUrl(urlStr, pdfName);
        if(inputStream != null){
            File file = new File(fileName);
            DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",
                    MediaType.ALL_VALUE, true, file.getName());

            try (OutputStream os = fileItem.getOutputStream()) {
                IOUtils.copy(inputStream, os);
            } catch (Exception e) {
                logger.error("输入流转DiskFileItem异常");
                throw new IllegalArgumentException("Invalid file: " + e, e);
            }

            multipartFile = new CommonsMultipartFile(fileItem);
        }
        return multipartFile;
    }
}

参考:
https://www.cnblogs.com/yadongliang/p/13578889.html

你可能感兴趣的:(Java操作Zip文件、inputstream转为multipartfile)