How encode in base64 a file generated with jspdf and html2canvas?

拜拜、爱过 提交于 2019-12-05 09:27:08

First, jsPDF is not native in javascript, make sure you have included proper source, and after having a peek on other references, I think you don't need btoa() function to convert doc.output(), just specify like this :

 doc.output('datauri');

Second, base-64 encoded string is possible to contain ' + ' , ' / ' , ' = ', they are not URL safe characters , you need to replace them or you cannot deal with ajax .

However, in my own experience, depending on file's size, it's easy to be hell long ! before reaching the characters' length limit of GET method, encoded string will crash your web developer tool first, and debugging would be difficult.

My suggestion, according to your jquery code

processData: false,
contentType: false

It is common setting to send maybe File or Blob object, just have a look on jsPDF, it is availible to convert your data to blob :

doc.output('blob');

so revise your code completely :

var img = canvas.toDataURL("image/png");
var doc = new jsPDF("l", "pt", "letter");
doc.addImage(img, 'JPEG',20,20);
var file = doc.output('blob');
var fd = new FormData();     // To carry on your data  
fd.append('mypdf',file);

$.ajax({
   url: '/model/send',   //here is also a problem, depends on your 
   data: fd,           //backend language, it may looks like '/model/send.php'
   dataType: 'text',
   processData: false,
   contentType: false,
   type: 'POST',
   success: function (response) {
     alter('Exit to send request');
   },
   error: function (jqXHR) {
     alter('Failure to send request');
   }
});

and if you are using php on your backend , you could have a look on your data information:

echo $_FILES['mypdf'];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!