【问题标题】:How to receive a binary image in javascript?如何在javascript中接收二进制图像?
【发布时间】:2016-12-30 18:48:42
【问题描述】:

我不知道我是否遗漏了什么,但我无法在 javascript 中接收图像(二进制)。我可以在 iPhone 和 Android 上做同样的事情(当然,用另一个角色),但如果我使用的是 javascript,则不能。

场景:

服务器端

我有一个存储图像的服务器。

代码:(test1.php)

$image_url = 'http://weburbanist.com/wp-content/uploads/2011/11/lorem-ipsum.jpg';


$bin = file_get_contents($image_url);

echo $bin;

客户端(Javascript)

我通过 URL GET/POST 向服务器请求图像,但我无法使用 AJAX 请求在 Javascript 中接收它。我想把它存储在一个 .

代码:

var activeXhr = new XMLHttpRequest();

activeXhr.open('GET', 'test1.php', true);

activeXhr.onreadystatechange = function()
{
    if(activeXhr.readyState == 4){
       var bin_img = activeXhr.responseText;
       var dataURL="data:image/jpeg;base64,"+bin_img;

       $('#test_img').attr('src',dataURL);
    }
};
activeXhr.send(null);

问题:

我无法转换以 BASE64 或使用 btoa 接收的数据(返回空)

问题:

如何在 JAVASCRIPT 中接收原始图像?

【问题讨论】:

标签: javascript image


【解决方案1】:

既然您已经在使用 jQuery,为什么不使用它的 Ajax 功能来处理请求呢?

这也短得多:

$.get('test1.php').done(function (r) {
  // r is your raw image data;
});

在 php 中设置 'Content-Type' 标头是否合适:

<?php 

$image_url = 'http://weburbanist.com/wp-content/uploads/2011/11/lorem-ipsum.jpg';

$bin = file_get_contents($image_url);

header('Content-Type: image/jpeg');

die($bin); // use die/exit for safer output

您是否考虑过像这样从 php 提供 Base64 数据:

die(base64_encode( $bin ));

【讨论】:

    猜你喜欢
    • 2018-08-07
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 2021-05-09
    • 2014-03-29
    • 1970-01-01
    • 2022-11-07
    相关资源
    最近更新 更多