Java操作Zip文件、inputstream轉(zhuǎn)為multipartfile

一、CommonsMultipartFile

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>
@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相關(guān)依賴


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>
import org.springframework.mock.web.MockMultipartFile;

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

三、從網(wǎng)絡(luò)url中操作zipFile

  • 網(wǎng)絡(luò)text文件為pdf和流水號的映射
20211013_7935015_001_15000001903734_1634117754785_0.pdf 8043432110131215777753
20211013_7935016_008_15000001903734_1634117754402_0.pdf 8043432110131215777753
  • zip中的pdf文件


    zip中的pdf文件

步驟:

  • 1、從網(wǎng)絡(luò)text文件中獲取pdf和流水號的映射,存入到HashMap中。

  • 2、從對應(yīng)的流水號中取出對應(yīng)的pdf文件名。

  • 3、通過pdf文件名從Zip文件中取出pdf文件,并包裝成MultipartFile,用于文件上傳到文件服務(wù)器。

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

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>
  • ZipFileUtils 工具類
public class ZipFileUtils {

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

    /**
     * 獲取網(wǎng)絡(luò)文件流
     * @param urlStr 網(wǎng)絡(luò)文件url
     * @return 返回輸入流
     * @throws IOException IO異常
     */
    private static InputStream downLoadFromUrl(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        //設(shè)置超時間為3秒
        conn.setConnectTimeout(3*1000);
        //防止屏蔽程序抓取而返回403錯誤
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //得到輸入流
        return conn.getInputStream();
    }

    /**
     * 獲取網(wǎng)絡(luò)文件流中的內(nèi)容,一次讀一行,并將空格拆開,返回
     * @param urlStr 網(wǎng)絡(luò)文件url
     * @return 返回pdf文件名和銀行流水號映射集合
     * @throws IOException IO異常
     */
    public static Map<String,List<String>> downLoadFileContentFromUrl(String urlStr) throws IOException {
        Map<String, List<String>> resultMap = new HashMap<>();
        InputStream inputStream = null;
        BufferedReader br = null;
        try {
            //得到輸入流
            inputStream = downLoadFromUrl(urlStr);
            //構(gòu)造一個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<String> 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 {
            //關(guān)閉流
            if(br != null){
                br.close();
            }
            if(inputStream != null){
                inputStream.close();
            }
        }
        return resultMap;
    }

    /**
     * 根據(jù)pdfName名稱,從網(wǎng)絡(luò)中獲取Zip中的pdf文件InputStream
     * @param urlStr Zip文件的下載url
     * @param pdfName pdf名稱
     * @return 返回輸入流
     * @throws IOException IO異常
     */
    public static InputStream downLoadZipFileFromUrl(String urlStr,String pdfName) throws IOException {
        //聲明字節(jié)輸出數(shù)組
        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())) {
                    //初始化字節(jié)輸出數(shù)組
                    byteOut = new ByteArrayOutputStream();
                    IOUtils.copy(zipIn, byteOut);
                    inputStream = new ByteArrayInputStream(byteOut.toByteArray());
                }
            }
            return inputStream;
        } finally {
            //關(guān)閉流
            if(byteOut != null){
                byteOut.close();
            }
            if(zipIn != null){
                zipIn.close();
            }
        }
    }

    /**
     * 根據(jù)pdfName名稱,從網(wǎng)絡(luò)中獲取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("輸入流轉(zhuǎn)DiskFileItem異常");
                throw new IllegalArgumentException("Invalid file: " + e, e);
            }

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

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容