猿问

如何使用javascript发送本地图像并在PHP中接收它

我们有一个本地系统,我想制作一个从中提取图像(' http://localhost/system_analysis.png ')并发送到 php 脚本的页面。


我有这个使用 FileReader 类的代码:


function fileAsDataURL(file) {

   var reader = new FileReader();

   reader.readAsDataURL(file);

   reader.onload = function () {

     return (reader.result;

   };

   reader.onerror = function (error) {

     return 0;

   };

}


var xhr = new XMLHttpRequest();

xhr.open("POST", MY_API, true);

xhr.setRequestHeader('Content-Type', 'application/json');

xhr.send(JSON.stringify({

    value: fileAsDataURL('http://localhost/system_analysis.png')

}));

我试过了,但我无法让它工作


慕盖茨4494581
浏览 148回答 1
1回答

慕容3067478

好吧,简单来说,你应该分两步思考:将图像转换为 base64 字符串。将其发送到 PHP API,该 API 将处理请求并将字符串转换回普通图像文件。1. 将在本地服务器上运行的文件:A. 将图像转换为 base64 字符串:function fileAsDataURL(url, callback) {  var xhr = new XMLHttpRequest();  xhr.onload = function() {    if (this.status == 200){      var reader = new FileReader();      reader.onloadend = function() {        callback(reader.result);      }      reader.readAsDataURL(xhr.response);    } else callback(0);  };  xhr.open('GET', url);  xhr.responseType = 'blob';  xhr.send();}B. 将 base64 字符串发布到您的 API 的函数:function sendImg(name, value) {  var xhr = new XMLHttpRequest();  xhr.open("POST", 'http://YOUR_API_SERVER_HERE', true);  xhr.setRequestHeader('Content-Type', 'application/json');  xhr.send(JSON.stringify({      name: name,      value: value  }))}C. 调用函数fileAsDataURL并将结果传递给函数sendImg:fileAsDataURL('http://localhost/system_analysis.png', function(dataUrl) {  sendImg('system_analysis.png', dataUrl);});2.API文件:$entityBody = file_get_contents('php://input');$entityBody = json_decode($entityBody);$data = explode(',', $entityBody->value);file_put_contents('PATH_TO_SAVE_IMAGE/'.$entityBody->name, base64_decode($data[1]));
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答