How to upload image canvas

0

I get the result of an image through this function this.canvas.toDataURL('png') , this function generates the image normally, the points are:

  • How to upload this to the PHP server using jQuery?
  • Is the correct way to upload? Will not you bring me damages because it is not a normal upload, with form input etc ...?
asked by anonymous 23.05.2016 / 14:32

2 answers

1
  

How to upload this to the PHP server using jQuery?

It's quite simple: Convert your canvas to blob and send an Ajax, with a small modification to the settings.

 function ajaxUpload(options) {
      options = $.extend({}, {contentType: false, cache: false, processData: false}, options);
      return $.ajax(options);
 }

 canvas.toBlob(function (blob) {

     var data = new FormData();
     data.append('imagem', blob);

     ajaxUpload({url: '/upload.php', data: data}).success(function () {
        console.log('upload concluído com sucesso');
     });
 });
  

Is it the right way to upload? Will not you bring me damages for not being a normal upload, with form input etc ...?

Well, the only difference I see is that you will always have to use ajax. Furthermore, with input , usually in upload submission, the filename is sent, other than blob , which does not have the filename of the source file, but in this case could be solved in a simple way: Placing the third parameter in the .append call:

  data.append('imagem', blob, 'imagem.jpg')

In addition, there are no "problems", but differences.

    
13.07.2018 / 02:59
0

How to upload this to the PHP server using jQuery?

First you need a .php file with the function to decode the base 64 string of the image to add it to a file on the server. Then you request or post data to this .php file, with the image in base64 . Success.

~~ Example ~~

jQuery:

$.post({

    data: {

        // Manda a imagem em base 64
        base64: canvas.toDataURL()

    },

    // O arquivo .php com a função citada
    url: "addimage.php"

});

PHP:

<?php


    // Ignora todos os caracters até a primeira vírgula depois de ";" (semicolon)

    $png = substr(
                $_POST['base64'],
                strpos($_POST['base64'], ";") + 1
    );

    $png = substr(
                $png,
                strpos($png, ",") + 1
    );

    // Cria (ou substitui, caso existente) a imagem no servidor
    file_put_contents('img.png', base64_decode($_POST['base_64']));

?>

Is the correct way to upload? Will not you bring me damages because it is not a normal upload, with form input etc ...?

It is common to send encrypted data with base64. If your string is very gigantic it may be slow on the server, but this is rare and hard to come by.

    
02.07.2016 / 23:17