问题
I'm trying to upload an image to a php server from a mobile app, converting file to blob and then uploading the blob with ajax. I get the image url after taking the photo with mobile. The uploaded file is empty. I think that should be an error while reading the file and converting to blob.
Client
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);
});
}
Server
<?php
$dir="uploads";
file_put_contents($dir."/image.jpg",$_POST['data']);
echo "Done";
?>
回答1:
Solved using base64 image with that
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.';
来源:https://stackoverflow.com/questions/23565025/upload-blob-data-to-php-server-retrieving-data-from-url