栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java 任意格式文件下载

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 任意格式文件下载

import lombok.SneakyThrows;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class DownloadUtil {

    private final static String FIREFOX = "firefox";

    @SneakyThrows
    public static void downloadChineseFileByOutputStream(HttpServletRequest req, HttpServletResponse response, String path, String fileName) {

        String agent = req.getHeader("USER-AGENT").toLowerCase();
        //根据浏览器类型处理文件名称    处理火狐浏览器下载文件名乱码
        if (agent.toLowerCase().indexOf(FIREFOX) > 0) {
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        } else {
            //其他浏览的中文名称编码
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        }
        //设置content-disposition响应头控制浏览器以下载的形式打开文件,中文文件名要使用URLEncoder.encode方法进行编码,否则会出现文件名乱码
        response.reset();
        response.setHeader("content-disposition", "attachment;filename=" + fileName);
        response.setContentType("application/octet-stream");
        URL url = new URL(path);
        HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        //设置是否要从 URL 连接读取数据,默认为true
        uc.setDoInput(true);
        uc.connect();
        InputStream in = uc.getInputStream();
        int len = 0;
        byte[] buffer = new byte[1024];
        OutputStream out = response.getOutputStream();
        while ((len = in.read(buffer)) > 0) {
            //将缓冲区的数据输出到客户端浏览器
            out.write(buffer, 0, len);
            out.flush();
        }
        out.close();
        in.close();
    }
}


//调用
String[] split = url.split("/");
String name = split[split.length - 1];
DownloadUtil.downloadChineseFileByOutputStream(request, response, url, name);
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/671647.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号