Upload a base64 image using Ajax

My client offers the user to select an image, crop and resize it, and then display it (in the <img>DOM element ).
If the image is in order, the user can upload it to the server so that it can be saved.

I want to do a download thanks to an Ajax request.

I found a ton of examples on the Internet to download the original image obtained from the client PC. For example:

$( '#my-form' )
  .submit( function( e ) {
    $.ajax( {
      url: 'http://host.com/action/',
      type: 'POST',
      data: new FormData( this ),
      processData: false,
      contentType: false
    } );
    e.preventDefault();
  } );

This works correctly if I decide to upload an image obtained through form input.

( <img>) .
base64 ( : croppie.js ).

, Ajax.

, img - :

var url = 'http://host.com/action/';
var data = {};
data.img = $('img#generated-image').attr('src');

$.ajax({url: url, type: "POST", data: data})
  .done(function(e){
    // Do something
  });
// RESULTS in a empty data.img on the server side.

, "img". , , ...

, , base64 , Ajax , .

.

, xmlHTTP POST. , .

EDIT2

post_max_size 8M php.ini, 24K. .
PHP Symfony2.
, Symfony2.

+4
2

, base64 Blob, Ajax formData . (base64 33% , ), base64 (- - ).

base64ToBlob .

function base64ToBlob(base64, mime) 
{
    mime = mime || '';
    var sliceSize = 1024;
    var byteChars = window.atob(base64);
    var byteArrays = [];

    for (var offset = 0, len = byteChars.length; offset < len; offset += sliceSize) {
        var slice = byteChars.slice(offset, offset + sliceSize);

        var byteNumbers = new Array(slice.length);
        for (var i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }

        var byteArray = new Uint8Array(byteNumbers);

        byteArrays.push(byteArray);
    }

    return new Blob(byteArrays, {type: mime});
}

JS:

var url = "url/action";                
var image = $('#image-id').attr('src');
var base64ImageContent = image.replace(/^data:image\/(png|jpg);base64,/, "");
var blob = base64ToBlob(base64ImageContent, 'image/png');                
var formData = new FormData();
formData.append('picture', blob);

$.ajax({
    url: url, 
    type: "POST", 
    cache: false,
    contentType: false,
    processData: false,
    data: formData})
        .done(function(e){
            alert('done!');
        });

Symfony2 :

$picture = $request->files->get('picture');
+24

Nitseg . , , auth ajax. , Nitseg .

var formData = new FormData();
var token = "<YOUR-TOKEN-HERE>";
formData.append("uploadfile", mediaBlob);        

jQuery.ajax({
    url: url,
    type: "POST",
    cache: false,
    contentType: false,
    processData: false,
    data: formData,
    beforeSend: function (xhr){ 
        xhr.setRequestHeader("Authorization", "Bearer " + token); 
    }
})
.done((e) => {
    // It is done.
})
.fail((e) => {
    // Report that there is a problem!
}); 
+1

Source: https://habr.com/ru/post/1624197/


All Articles