Upload Blob data to php server, retrieving data from url [duplicate]

折月煮酒 提交于 2021-02-07 19:26:41

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!