使用php将blob数据转换为图像

时间:2016-11-01 08:39:29

标签: javascript php image blob

我有一个页面,我使用此代码将输入类型=文件的图像上传到图像标记

$('#profile-image-upload').change( function(event) {
var path = URL.createObjectURL(event.target.files[0]);

$("#image").attr('src',URL.createObjectURL(event.target.files[0]));

这给了我一个像blob这样的路径的bolb数据:http://localhost:8080/467d02c9-0af0-448a-a239-69e8d4037dd1。我的图像存储在路径变量

中保存的blob数据中

现在我也希望这个图像文件保存在我的服务器目录中,并且我使用ajax将其发送到我的服务器

var ajax;

    if (window.XMLHttpRequest)  // For modren Browsers
      ajax=new XMLHttpRequest();

    else
      ajax=new ActiveXObject("Microsoft.XMLHTTP"); // For IE5 & IE8

      ajax.open("POST","../UploadImg.php",true);

      ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
     var data=  "path="+path+"&type="+user+"&id="+id+"&extent="+extent;


     //path = blob data       
     //user = user name
     //id = user id
     //extent = extension of image

      ajax.onreadystatechange=function()
      {
        if (ajax.readyState==4 && ajax.status==200){
            alert(ajax.responseText);
        }
      }

     ajax.send(data);

});

我的服务器端编码是

$img_ff = $_POST["path"]; // blob path
$user = $_POST["type"];
$id = $_POST["id"];
$extension = $_POST["extent"];

$dst_img= $user.$id.".".$extention;  // for example user17.png
$dst_path= "localhost:8080/live4others/images/";

$dst_cpl = $dst_path . $dst_img;   

if(move_uploaded_file($dst_cpl, $img_ff)){
        echo "yes";
    }else{
        echo "error";
    }

    if( file_put_contents( $img_ff, $dst_cpl)){
        echo "yes";
    }else{
        echo "error";
    }

这两种方法都不起作用。请告诉我我在哪里做错了。他们给出错误并说给定路径无效。

1 个答案:

答案 0 :(得分:0)

你可以试试这个。我使用相同但使用 blob 只是在提交之前预览图像/视频。

<强> Jquery的

$('#<formId>').on('submit', function(e) {
    e.preventDefault();
    $.ajax({
        url: "../UploadImg.php",
        type: "POST",
        data:  new FormData(this),
        dataType: "json",
        contentType: false,
        cache: false,
        processData:false,
        success: function(response){
            console.log(response);
        }, 
        error : function (jqXHR, textStatus, errorThrown) {
        }
    });
});

PHP - UploadImg.php

$tmpFile  = $_FILES['<fileElementName>'];

$absolutePathOfdestinationFolder = '/var/www/<projectDocRoot>/images/'.$user.$id.".".$extention;

if(move_uploaded_file($tmpFile['tmp_name'], $absolutePathOfdestinationFolder)){
    echo "yes";
}else{
    echo "error";
}
相关问题