使用文件流的形式在浏览器下载word文档

这段代码展示了如何通过HTTP从指定URL下载Word文档,并在浏览器中以文件流形式保存,利用Content-disposition设置附件名称,确保下载过程正确。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、使用文件流的形式在浏览器下载word文档

String path = "http://172.16.228.130:7300/document/d9dd1ec7e72d4fc6a9e50ef1a930f34d.docx";
String fileName = "测试文档";
//远程调用文档流下载文档
BufferedOutputStream bf = null;
String fileName = fileName;
try {
    response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

    bf = new BufferedOutputStream(response.getOutputStream());

    if (path.startsWith("http://")) {
        bf.write(this.httpConverBytes(path);
    }

} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (bf != null) {
        bf.close();
        bf.flush();
    }
}
public byte[] httpConverBytes(String path) {
    BufferedInputStream in = null;
    ByteArrayOutputStream out = null;
    URLConnection conn = null;

    try {
        URL url = new URL(path);
        conn = url.openConnection();

        in = new BufferedInputStream(conn.getInputStream());

        out = new ByteArrayOutputStream(1024);
        byte[] temp = new byte[1024];
        int size = 0;
        while ((size = in.read(temp)) != -1) {
            out.write(temp, 0, size);
        }
        byte[] content = out.toByteArray();
        return content;
    } catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值