上传Blob数据到php服务器,从url检索数据


Upload Blob data to php server, retrieving data from url

我试图从移动应用程序上传图像到php服务器,将文件转换为blob,然后用ajax上传blob。我用手机拍照后得到图像url。上传的文件为空。我认为这应该是一个错误,而读取文件和转换为blob。

var blob;
function get(){
var image = document.getElementById('image');
var file=image.src;
var oReq = new XMLHttpRequest();
oReq.open("GET", file, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(oEvent) {
   blob = new Blob([oReq.response], {type: "image/jpg"});
};

oReq.send();

var fd = new FormData();
fd.append("file", blob, "filename.jpg");
$.ajax({
    type: 'POST',
    url: 'http://site/upload.php',
    data: fd,
    processData: false,
    contentType: false
}).done(function(data) {
       alert(data);
});
}
服务器

<?php
$dir="uploads";
file_put_contents($dir."/image.jpg",$_POST['data']);
    echo "Done";  
?>

使用base64图像解决

define('UPLOAD_DIR', 'images/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';