admin管理员组

文章数量:1387429

In one of my application i am cropping the image using /

The resultant cropped image am getting in the base64 dataURL format, but i required that to be in file object format.

How to convert the dataURL to file either in client side or server side.

In one of my application i am cropping the image using http://fengyuanchen.github.io/cropper/

The resultant cropped image am getting in the base64 dataURL format, but i required that to be in file object format.

How to convert the dataURL to file either in client side or server side.

Share Improve this question asked Jan 20, 2015 at 9:32 madhuchennamadhuchenna 1011 silver badge2 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 4

Use Blob instead of the deprecated BlobBuilder. The code is very clean and simple. (Manuel Di Iorio's code is deprecated.)

function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {type:mime});
}
//test:
//var blob = dataURLtoBlob('data:text/plain;base64,YWFhYWFhYQ==');

Data URI scheme

How to convert dataURL to file object in javascript?

function dataURItoBlob(dataURI) {
    // convert base64 to raw binary data held in a string
    // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
    var byteString = atob(dataURI.split(',')[1]);

    // separate out the mime ponent
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to an ArrayBuffer
    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    // write the ArrayBuffer to a blob, and you're done
    var bb = new BlobBuilder();
    bb.append(ab);
    return bb.getBlob(mimeString);
}

Then just append the blob to a new FormData object and post it to your server using ajax:

var blob = dataURItoBlob(someDataUrl);
var fd = new FormData(document.forms[0]);
var xhr = new XMLHttpRequest();

fd.append("myFile", blob);
xhr.open('POST', '/', true);
xhr.send(fd);

Thats my validation for input.

$data = $_POST['thumb'];
$uriPhp = 'data://' . substr($data, 5);

if ( base64_encode(base64_decode($uriPhp))){
    $_POST['thumb'] = $uriPhp;
} 

for saving I am using : http://www.verot/php_class_upload.htm

$foo = new Upload($_POST['thumb']);
    if ($foo->uploaded) {
      // save uploaded image with a new name
      $foo->file_new_name_body = $name;
      $foo->image_convert = 'png';
      $foo->Process("uploads/");
    }

本文标签: javaconvert dataURL to file using javascriptStack Overflow