將多個文件導出到zip包

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>io</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.3.2.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <!-- web模塊-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--日誌-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.12</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
server:
  port: 8023
package com.sadhu;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @ClassName IoApplication
 * @Description TODO
 * @Author sadhu
 * @Date 2022/2/25 9:02
 **/
@SpringBootApplication
public class IoApplication {
    public static void main(String[] args) {
        SpringApplication.run(IoApplication.class, args);
    }
}
package com.sadhu.controller;

import cn.hutool.core.util.CharsetUtil;
import com.sadhu.service.ZipService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.zip.ZipOutputStream;

/**
 * @ClassName ZipController
 * @Description TODO
 * @Author sadhu
 * @Date 2022/2/25 9:05
 **/
@RestController
@RequestMapping("/file")
public class ZipController {
    @Autowired
    private ZipService zipService;

    /**
     * 下載zip包
     *
     * @param response
     * @param fileName
     */
    @RequestMapping(value = "/downLoadZipFile", method = RequestMethod.GET)
    public void downLoadZipFile(HttpServletResponse response, @RequestParam("fileName") String fileName) throws IOException {
        // 導出到瀏覽器的文件名
        String zipFileName = fileName + ".zip";
        // zip包輸出流
        ZipOutputStream zipOutputStream = null;
        try {

            // 清除buffer,清除首部的空白行
            response.reset();
            // 不同類型的文件對應不同的MIME類型
            response.setContentType("application/x-zip-compressed");
            // 設置編碼格式
            response.setCharacterEncoding("utf-8");
            // 設置響應頭
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(zipFileName, CharsetUtil.UTF_8));
            // 創建zip包輸出流,並設置編碼格式
            zipOutputStream = new ZipOutputStream(response.getOutputStream(), Charset.forName(CharsetUtil.UTF_8));
            // 將文件流寫入輸出流
            zipService.downLoadZipFile(zipOutputStream);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 完成編寫ZIP輸出流的內容而不關閉底層流
            zipOutputStream.finish();
            if (null != zipOutputStream) {
                // 關閉輸出流,異常直接拋出
                zipOutputStream.close();
            }
        }
    }
}
package com.sadhu.service;

import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @ClassName ZipService
 * @Description TODO
 * @Author sadhu
 * @Date 2022/2/25 9:06
 **/
@Service
public class ZipService {
    /**
     * 將文件流寫入輸出流
     *
     * @param zipOutputStream
     */
    public void downLoadZipFile(ZipOutputStream zipOutputStream) {
        // 將兩個文件壓入同一個壓縮包
        String filePath = "C:\\Users\\ASUS\\Desktop\\sadhu";
        String fileName_1 = "test_1.txt";
        String fileName_2 = "test_2.txt";
        // 文件輸入流
        FileInputStream fileInputStream_1 = null;
        FileInputStream fileInputStream_2 = null;
        // 緩衝區
        byte[] buf = new byte[1024];
        try {
            // 獲取文件輸入流
            fileInputStream_1 = new FileInputStream(filePath + "\\" + fileName_1);
            fileInputStream_2 = new FileInputStream(filePath + "\\" + fileName_2);
            // 在zip包創建fileName_1的文件
            zipOutputStream.putNextEntry(new ZipEntry(fileName_1));
            // 從頭開始,將文件輸入流轉爲zip包輸出流
            int read = 0;
            while ((read = fileInputStream_1.read(buf)) != -1) {
                zipOutputStream.write(buf, 0, read);
            }
            // 關閉當前的ZIP條目並定位流以讀取下一個條目
            zipOutputStream.closeEntry();
            // --------------------------
            // 在zip包創建fileName_2的文件
            zipOutputStream.putNextEntry(new ZipEntry(fileName_2));
            // 從頭開始,將文件輸入流轉爲zip包輸出流
            read = 0;
            buf = new byte[1024];
            while ((read = fileInputStream_2.read(buf)) != -1) {
                zipOutputStream.write(buf, 0, read);
            }
            // 關閉當前的ZIP條目並定位流以讀取下一個條目
            zipOutputStream.closeEntry();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

// 在項目中,通過feign調用其他服務接口,獲取到流,一樣的可以將流轉換成輸出流,然後輸出瀏覽器。

// 在定義feign接口的時候用 Response 對象去接返回,而對應服務返回值爲void,並且將流輸出給Response
Response response = "feign接口";
// 轉換爲輸入流
InputStream inputStream = response.body().asInputStream();
// 然後再轉輸出流
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章