1 回答

TA贡献1773条经验 获得超3个赞
好吧,简单来说,你应该分两步思考:
将图像转换为 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]));
添加回答
举报