后端 图片地址下载后 返回流给前端

本文介绍了如何在Java中通过`sendGetFaceURL`方法发送GET请求,包括参数传递、URL构建、身份验证以及处理返回的JSON数据。

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

/**
     * 
     * @param url 地址
     * @param param  参数
     * @param username  认证用户
     * @param password  密码
     * @param type  json
     * @param httpServletResponse  
     * @throws IOException
     */ 
public static void sendGetFaceURL(String url, String param, String username, String password, String type, HttpServletResponse httpServletResponse) throws IOException {
        BufferedReader in = null;
        try {
             //认证
            String wwwAuth = sendGetOrPost(url, param, "get");       // 发起一次授权请求
            if (wwwAuth.startsWith("WWW-Authenticate:")) {
                wwwAuth = wwwAuth.replaceFirst("WWW-Authenticate:", "");
            }
            nc++;
            String urlNameString = url + (StringUtils.isNotEmpty(param) ? "?" + param : "");

            //请求
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            nection.setRequestProperty("accept", "application/json;charset=UTF-8");
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            // connection.connect();
            // 流写入
            InputStream inputStream = connection.getInputStream();
            writeFile(httpServletResponse, inputStream);
        } catch (Exception e) {
            nc = 0;
            throw new RuntimeException(e);
        } finally {
            try {
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

### 前端接收后端文件并实现自动下载 为了实现在前端接收到由后端返回的文件并触发浏览器自动下载该文件的功能,可以采用基于 `axios` 发起 HTTP 请求的方式获取文件,并利用 JavaScript 的 `Blob` API 创建文件对象。之后借助 `<a>` 标签模拟点击事件完成文件下载操作。 下面是一个完整的 Vue.js 方法用于发起请求以及处理响应中的文件: ```javascript async function downloadFile() { try { const response = await axios({ method: 'get', url: '/api/download', // 后端提供文件的API路径 responseType: 'blob' // 显式指定期望得到的是二进制大对象(BLOB) }); // 获取文件名可以从header中读取content-disposition字段解析出来, // 或者直接定义一个默认名称。 let filename = "default_filename"; const contentDisposition = response.headers['content-disposition']; if (contentDisposition) { const matches = /filename=([^;]+)/.exec(contentDisposition); if (matches != null && matches[1]) { filename = decodeURIComponent(matches[1].trim()); } } // 构建URL对象供<a>标签使用 const blob = new Blob([response.data]); const link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = filename; // 将链接添加至DOM树以便触发click() document.body.appendChild(link); // 执行点击动作启动下载程 link.click(); // 清理临时创建的对象防止内存泄漏 window.URL.revokeObjectURL(link.href); document.body.removeChild(link); } catch (err) { console.error(err.message || err); } } ``` 此方法适用于大多数场景下的文件下载需求,无论是文档还是图片等其他类型的文件都可按照上述逻辑进行适配调整[^1]。 对于特定 MIME 类型的支持,比如 Excel 文件,则需确保设置正确的 Content-Type 头部信息给 `Blob` 构造器,例如 `"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"` 表示 `.xlsx` 文件格式[^3]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值