将Blob数据上传到php服务器,从url检索数据 [英] Upload Blob data to php server, retrieving data from url

查看:38
本文介绍了将Blob数据上传到php服务器,从url检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图像从移动应用程序上传到php服务器,将文件转换为blob,然后使用ajax上传blob.使用手机拍照后,我得到了图片网址.上传的文件为空.我认为在读取文件并转换为Blob时应该是一个错误.

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.

客户

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图像解决此问题

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.';

这篇关于将Blob数据上传到php服务器,从url检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆