java瀏覽器下載

JAVA讀取指定路徑下文件,實現模擬瀏覽器下載文件,核心代碼如下:

/**
     * 瀏覽器下載
     *
     * @param sourceFilePath 源文件路徑:"D:\\demo.txt"
     * @param fileName       下載生成的文件名
     * @param response       響應瀏覽器
     */
    public void browserDownload(String sourceFilePath, String fileName, HttpServletResponse response) {
        try (InputStream is = new FileInputStream(sourceFilePath);
             OutputStream os = response.getOutputStream();
             BufferedInputStream bis = new BufferedInputStream(is);
             BufferedOutputStream bos = new BufferedOutputStream(os)) {

            response.setContentType("application/octet-stream");
            response.setHeader("content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GBK"), StandardCharsets.ISO_8859_1));
            int length = 0;
            byte[] temp = new byte[1024 * 10];
            while ((length = bis.read(temp)) != -1) {
                bos.write(temp, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 

發佈了30 篇原創文章 · 獲贊 14 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章