Java 將文件/網(wǎng)絡文件轉換成流下載

將網(wǎng)絡文件/本地文件轉換成流供前端下載
或者將多個網(wǎng)絡文件/本地文件打zip壓縮包給前端下載


import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
 
 
public class FileUtil {
    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
 
    private static MimetypesFileTypeMap mimetypesFileTypeMap;
 
    /**
     * 下載http文件流
     *
     * @param urlStr
     * @param request
     * @param response
     * @param fileName
     * @return
     */
    public static void downloadHttpFile(String urlStr, HttpServletRequest request, HttpServletResponse response, String fileName) {
        ServletOutputStream out = null;
        InputStream inputStream = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //得到輸入流
            inputStream = conn.getInputStream();
            //獲取自己數(shù)組
            byte[] getData = FileUtil.inputStreamToByte(inputStream);
            // 下載
            out = response.getOutputStream();
            long contentLength = getData.length;
            FileUtil.setResponse(fileName, contentLength, request, response);
            out.write(getData);
            out.flush();
        } catch (Exception e) {
            throw new RuntimeException("下載失敗!");
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    //File、FileInputStream 轉換為byte數(shù)組
    public static byte[] inputStreamToByte(InputStream inputStream) {
        try {
            byte[] buffer = new byte[1024];
            int len = 0;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while ((len = inputStream.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            bos.close();
            return bos.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("文件轉換失敗!");
        }
    }
 
    /**
     * 下載文件流
     *
     * @param file
     * @param request
     * @param response
     * @param fileName
     * @return
     */
    public static void downloadFile(File file, HttpServletRequest request, HttpServletResponse response, String fileName) {
        if (file != null && file.exists() && file.length() > 0L) {
            try {
                RandomAccessFile randomFile = new RandomAccessFile(file, "r");
                Throwable var5 = null;
 
                Object var54;
                try {
                    ServletOutputStream out = response.getOutputStream();
                    Throwable var7 = null;
 
                    try {
                        long contentLength = randomFile.length();
                        String range = request.getHeader("Range");
                        long start = 0L;
                        long end = 0L;
                        if (range != null && range.startsWith("bytes=")) {
                            String[] values = range.split("=")[1].split("-");
                            start = Long.parseLong(values[0]);
                            if (values.length > 1) {
                                end = Long.parseLong(values[1]);
                            }
                        }
 
                        int requestSize;
                        if (end != 0L && end > start) {
                            requestSize = Long.valueOf(end - start + 1L).intValue();
                        } else {
                            requestSize = 2147483647;
                        }
 
                        FileUtil.setResponse(fileName, contentLength, request, response);
 
                        randomFile.seek(start);
 
                        byte[] buffer;
                        for (int needSize = requestSize; needSize > 0; needSize -= buffer.length) {
                            buffer = new byte[1024];
                            int len = randomFile.read(buffer);
                            if (needSize < buffer.length) {
                                out.write(buffer, 0, needSize);
                            } else {
                                out.write(buffer, 0, len);
                                if (len < buffer.length) {
                                    break;
                                }
                            }
                        }
 
                        out.flush();
                        var54 = null;
                    } catch (Throwable var47) {
                        var7 = var47;
                        throw var47;
                    } finally {
                        if (out != null) {
                            if (var7 != null) {
                                try {
                                    out.close();
                                } catch (Throwable var46) {
                                    var7.addSuppressed(var46);
                                }
                            } else {
                                out.close();
                            }
                        }
 
                    }
                } catch (Throwable var49) {
                    var5 = var49;
                    throw var49;
                } finally {
                    if (randomFile != null) {
                        if (var5 != null) {
                            try {
                                randomFile.close();
                            } catch (Throwable var45) {
                                var5.addSuppressed(var45);
                            }
                        } else {
                            randomFile.close();
                        }
                    }
 
                }
            } catch (IOException var51) {
                logger.debug(var51.getMessage(), var51);
                throw new RuntimeException(var51.getMessage());
            }
        } else {
            throw new RuntimeException("文件為空或不存在瘟栖!");
        }
    }
 
    /**
     * @param fileName
     * @param contentLength
     * @param request
     * @param response
     * @return
     */
    public static void setResponse(String fileName, long contentLength, HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType(FileUtil.getContentType("0.jpg"));
            boolean isPreview = "preview".equalsIgnoreCase(request.getParameter("source"));
            response.addHeader("Content-Disposition", (!isPreview ? "attachment; " : "") + "filename*=utf-8'zh_cn'" + URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("Accept-Ranges", "bytes");
 
            String range = request.getHeader("Range");
            if (range == null) {
                response.setHeader("Content-Length", String.valueOf(contentLength));
            } else {
                response.setStatus(206);
                long requestStart = 0L;
                long requestEnd = 0L;
                String[] ranges = range.split("=");
                if (ranges.length > 1) {
                    String[] rangeDatas = ranges[1].split("-");
                    requestStart = Long.parseLong(rangeDatas[0]);
                    if (rangeDatas.length > 1) {
                        requestEnd = Long.parseLong(rangeDatas[1]);
                    }
                }
 
                long length = 0L;
                if (requestEnd > 0L) {
                    length = requestEnd - requestStart + 1L;
                    response.setHeader("Content-Length", String.valueOf(length));
                    response.setHeader("Content-Range", "bytes " + requestStart + "-" + requestEnd + "/" + contentLength);
                } else {
                    length = contentLength - requestStart;
                    response.setHeader("Content-Length", String.valueOf(length));
                    response.setHeader("Content-Range", "bytes " + requestStart + "-" + (contentLength - 1L) + "/" + contentLength);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("response響應失敗!");
        }
    }
 
    public static String getContentType(String fileName) {
        if (mimetypesFileTypeMap == null) {
            mimetypesFileTypeMap = new MimetypesFileTypeMap();
        }
 
        return mimetypesFileTypeMap.getContentType(fileName);
    }
 
    /**
     * 將磁盤的多個文件打包成壓縮包并輸出流下載
     *
     * @param pathList
     * @param request
     * @param response
     */
    public static void zipDirFileToFile(List<Map<String, String>> pathList, HttpServletRequest request, HttpServletResponse response) {
        try {
            // 設置response參數(shù)并且獲取ServletOutputStream
            ZipArchiveOutputStream zous = getServletOutputStream(response);
 
            for (Map<String, String> map : pathList) {
                String fileName = map.get("name");
                File file = new File(map.get("path"));
                InputStream inputStream = new FileInputStream(file);
                setByteArrayOutputStream(fileName, inputStream, zous);
            }
            zous.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 將網(wǎng)絡url資源文件的多個文件打包成壓縮包并輸出流下載
     *
     * @param pathList
     * @param request
     * @param response
     */
    public static void zipUrlToFile(List<Map<String, String>> pathList, HttpServletRequest request, HttpServletResponse response) {
        try {
            // 設置response參數(shù)并且獲取ServletOutputStream
            ZipArchiveOutputStream zous = getServletOutputStream(response);
 
            for (Map<String, String> map : pathList) {
                String fileName = map.get("name");
                InputStream inputStream = getInputStreamFromUrl(map.get("path"));
                setByteArrayOutputStream(fileName, inputStream, zous);
            }
            zous.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    private static ZipArchiveOutputStream getServletOutputStream(HttpServletResponse response) throws Exception {
        String outputFileName = "文件" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".zip";
        response.reset();
        response.setHeader("Content-Type", "application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(outputFileName, "UTF-8"));
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        // TODO 下面兩行代碼可能會產生 IO 錯誤,屆時注釋掉該代碼即可
        response.addHeader("Access-Control-Allow-Origin", "*");//允許所有來源訪同
        response.addHeader("Access-Control-Allow-Method", "POST,GET");
        ServletOutputStream out = response.getOutputStream();
 
        ZipArchiveOutputStream zous = new ZipArchiveOutputStream(out);
        zous.setUseZip64(Zip64Mode.AsNeeded);
        return zous;
    }
 
    private static void setByteArrayOutputStream(String fileName, InputStream inputStream, ZipArchiveOutputStream zous) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        baos.flush();
        byte[] bytes = baos.toByteArray();
 
        //設置文件名
        ArchiveEntry entry = new ZipArchiveEntry(fileName);
        zous.putArchiveEntry(entry);
        zous.write(bytes);
        zous.closeArchiveEntry();
        baos.close();
    }
 
    /**
     * 通過網(wǎng)絡地址獲取文件InputStream
     *
     * @param path 地址
     * @return
     */
    private static InputStream getInputStreamFromUrl(String path) {
        URL url = null;
        InputStream is = null;
        try {
            url = new URL(path);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.connect();
            is = conn.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}


    @GetMapping(value = "/down/file")
    public void downloadFileStream(HttpServletRequest request, HttpServletResponse response) {
        // 文件本地位置
        String filePath = "D:/新建文本文檔.txt";
        // 文件名稱
        String fileName = "測試文件.txt";
        File file = new File(filePath);
        FileUtil.downloadFile(file, request, response, fileName);

        // 瀏覽器訪問:http://x.x.x.x/test/down/file
    }



    @GetMapping(value = "/down/http")
    public void downloadFileHttpStream(HttpServletRequest request, HttpServletResponse response) {
        // 文件網(wǎng)絡地址
        String urlStr = "https://code.jquery.com/jquery-3.6.0.js";
        // 文件名稱
        String fileName = "測試文件.js";
        FileUtil.downloadHttpFile(urlStr, request, response, fileName);
        // 瀏覽器訪問:http://x.x.x.x/test/down/file/http
    }



    @GetMapping(value = "/down/zip")
    public void downloadZipStream(HttpServletRequest request, HttpServletResponse response) {
        List<Map<String, String>> mapList = new ArrayList<>();
        String basePath = "D:/新建文本文檔";
        // 模擬下載本地的5個文件顶伞,分別為測試文件1~5
        for (int i = 1; i <= 5; i++) {
            Map<String, String> map = new HashMap<>();
            map.put("path", basePath + ".docx");
            map.put("name", "測試文件_" + ".docx");
            mapList.add(map);
        }
        FileUtil.zipDirFileToFile(mapList, request, response);

        // 瀏覽器訪問:http://x.x.x.x/test/down/zip
    }
<script lang="ts" setup>
    import axios from 'axios'
    
    function download() {
      axios({
        method: "GET",
        url: `http://localhost:8080/test/down/http`,
        responseType: 'blob'
      }).then(res => {
        // 請求成功后處理流
        if(res.status === 200) {
          const blob = new Blob([res.data])
          const a = document.createElement('a');
          const url = URL.createObjectURL(blob); //創(chuàng)建下載的鏈接
          a.href = url;
          a.download = '自定義文件名.xlsx'; //下載后文件名
          document.body.appendChild(a);
          a.click(); //點擊下載
          document.body.removeChild(a); //下載完成移除元素
          window.URL.revokeObjectURL(url); //釋放掉blob對象
        }
      });
    }
</script>

<div>
  <div @click="download" style="width: 120px; height: 35px; border: 1px solid red;">點我下載</div>
</div>

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末说莫,一起剝皮案震驚了整個濱河市蝶溶,隨后出現(xiàn)的幾起案子储藐,更是在濱河造成了極大的恐慌,老刑警劉巖误阻,帶你破解...
    沈念sama閱讀 212,816評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件债蜜,死亡現(xiàn)場離奇詭異,居然都是意外死亡究反,警方通過查閱死者的電腦和手機寻定,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,729評論 3 385
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來精耐,“玉大人狼速,你說我怎么就攤上這事∝酝#” “怎么了向胡?”我有些...
    開封第一講書人閱讀 158,300評論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長沫浆。 經(jīng)常有香客問我捷枯,道長滚秩,這世上最難降的妖魔是什么专执? 我笑而不...
    開封第一講書人閱讀 56,780評論 1 285
  • 正文 為了忘掉前任,我火速辦了婚禮郁油,結果婚禮上本股,老公的妹妹穿的比我還像新娘。我一直安慰自己桐腌,他們只是感情好拄显,可當我...
    茶點故事閱讀 65,890評論 6 385
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著案站,像睡著了一般躬审。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上蟆盐,一...
    開封第一講書人閱讀 50,084評論 1 291
  • 那天承边,我揣著相機與錄音,去河邊找鬼石挂。 笑死博助,一個胖子當著我的面吹牛,可吹牛的內容都是我干的痹愚。 我是一名探鬼主播富岳,決...
    沈念sama閱讀 39,151評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼蛔糯,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了窖式?” 一聲冷哼從身側響起蚁飒,我...
    開封第一講書人閱讀 37,912評論 0 268
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎萝喘,沒想到半個月后飒箭,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,355評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡蜒灰,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 36,666評論 2 327
  • 正文 我和宋清朗相戀三年弦蹂,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片强窖。...
    茶點故事閱讀 38,809評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡凸椿,死狀恐怖,靈堂內的尸體忽然破棺而出翅溺,到底是詐尸還是另有隱情脑漫,我是刑警寧澤,帶...
    沈念sama閱讀 34,504評論 4 334
  • 正文 年R本政府宣布咙崎,位于F島的核電站优幸,受9級特大地震影響,放射性物質發(fā)生泄漏褪猛。R本人自食惡果不足惜网杆,卻給世界環(huán)境...
    茶點故事閱讀 40,150評論 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望伊滋。 院中可真熱鬧碳却,春花似錦、人聲如沸笑旺。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,882評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽筒主。三九已至关噪,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間乌妙,已是汗流浹背使兔。 一陣腳步聲響...
    開封第一講書人閱讀 32,121評論 1 267
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留冠胯,地道東北人火诸。 一個月前我還...
    沈念sama閱讀 46,628評論 2 362
  • 正文 我出身青樓,卻偏偏與公主長得像荠察,于是被迫代替她去往敵國和親置蜀。 傳聞我的和親對象是個殘疾皇子奈搜,可洞房花燭夜當晚...
    茶點故事閱讀 43,724評論 2 351

推薦閱讀更多精彩內容