How to send base64 image via ajax

2020-03-30 05:12发布

问题:

I am develop t-shirt constructor. When I send base64 data (canvas.toDataUrl()) via ajax POST method to server, I get base64 string with spaces.

For exmaple:

Send:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAhsAAAIbCAYAAABCJ1y9AAAgAElEQVR4Xuy9CbCmVXkuur7pn/bcczd00w2INAhBmdQ4EDNpHEi8gVMQcyKpc3NOck3lOKRyokmFUzmHSupgLG9MTFKpeK

Get:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAhsAA 
 AIbCAYAAABCJ1y9AAAgAElEQVR4Xuy9CbCmVXkuur7pn/b 
 cczd00w2INAhBmdQ4EDNpHEi8gVMQcyKpc3 NOck3lOKRyokmFUzmH SupgLG9MT   FKpeK

JS code:

var data = csrfParam + '=' + csrfToken + '&front_base64=' + frontImage
     + '&back_base64=' + backImage + '&product_id=' + currentProduct['id'] 
     + '&color_id=' + currentProductColorId + '&size_id=' + 
     currentProductSize;
 var xhr = new XMLHttpRequest();
 xhr.open('POST', '/constructor/add-to-cart/', true);
 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 xhr.send(data);
 xhr.onload = function () {console.log(xhr.responseText)}

white spacing screenshot

回答1:

use jquery ajax it will make your life a lot easier and the problem will be solved as well :

$.post('/constructor/add-to-cart/',{
      csrfParam : csrfToken,
      front_base64: frontImage,
      back_base64 : backImage,
      product_id : currentProduct['id'],
      color_id  : currentProductColorId,
      size_id : currentProductSize
    },function(response){
     console.log(response)
    });

and if you want view the base64 image in backend to check if its ok

<img src="/* base 64 string here */" />

rather then just viewing the string.



回答2:

I have understood my problem, I need to add encodeURIComponent() around base64. Thanks Jonathan Kuhn for help!