You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS 1.2.x升级至1.6+后,$http获取PNG图片代码失效求助

解决AngularJS 1.6+中$http获取PNG图片返回空的问题

修正后的代码

$http.get(src, {responseType: "arraybuffer"}).then(function(response){
    console.log("image content", response.data);
    // 可选:将arraybuffer转为可下载的PNG文件
    var blob = new Blob([response.data], {type: 'image/png'});
    var downloadUrl = URL.createObjectURL(blob);
    
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = 'downloaded-image.png';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(downloadUrl);
});

问题根源

AngularJS 1.6+对$http的Promise回调参数结构做了变更:

  • 在1.2.x版本中,then的回调函数直接接收响应数据data
  • 1.6+版本里,回调函数接收的是一个完整的响应对象,实际的图片二进制数据存储在该对象的data属性中

之前的代码直接打印data,其实是打印了整个响应对象(而非二进制内容),所以看起来日志为空。

额外注意事项

  • 确保目标图片地址不存在跨域限制,若为跨域请求,需服务器配置CORS允许相关请求方法和头信息
  • 确认responseType: "arraybuffer"配置正确,该参数在1.6+版本中仍需显式设置,否则会默认按文本解析二进制数据导致错误
  • 若需要触发下载,需将arraybuffer转为Blob对象,再通过URL.createObjectURL生成可下载链接

内容的提问来源于stack exchange,提问作者Jay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 06:25:23