简体   繁体   English

如何从ajax数据发送将pdf上载到服务器(使用jsPDF)

[英]how to upload pdf to server from ajax data send (using jsPDF)

I'm using jsPDF to generate a pdf on client-side. 我正在使用jsPDF在客户端生成pdf。 With the function doc.save('filename.pdf') I can download it. 使用函数doc.save('filename.pdf'),我可以下载它。 Now I need to save it on the server, so I'm sending the pdf data with .ajax() and receiving it with a PHP script but the images on the generated pdfURL doesn't show ( http://mydomain/tmp/test.pdf ); 现在,我需要将其保存在服务器上,因此我将使用.ajax()发送pdf数据,并使用PHP脚本进行接收,但是生成的pdfURL上的图像未显示( http:// mydomain / tmp / test.pdf ); only shows the text. 只显示文字。

Can you give me a hand please? 你能帮我一下吗?

My js code: 我的js代码:

//doc.save('test.pdf');  WORKS WELL
var pdf = doc.output();
$.ajax({
  method: "POST",
  url: "inc/test.php",
  data: {data: pdf},
}).done(function(data){
   console.log(data);
});

The PHP script: PHP脚本:

<?php
if(!empty($_POST['data'])){

    $data = $_POST['data'];
    print_r($data);

    file_put_contents( "../tmp/test.pdf", $data );
} else {
    echo "No Data Sent"; 
}
exit();
?>

This is the pdf generated after the php scripting proccess: http://control.edge-cdn.com.ar/tmp/test.pdf 这是在php脚本编写过程之后生成的pdf: http : //control.edge-cdn.com.ar/tmp/test.pdf

And this is the generated with the doc.save() function: http://control.edge-cdn.com.ar/repo/all.pdf Regards! 这是使用doc.save()函数生成的: http ://control.edge-cdn.com.ar/repo/all.pdf致谢!

SOLUTION : 解决方案

I was trying to send the pdf data as binary. 我试图将pdf数据作为二进制发送。 I just base64 encode the string, send it and them decode that on the php. 我只是对字符串进行base64编码,将其发送,然后在php上对其进行解码。

JS: JS:

    var pdf = btoa(doc.output()); 
    $.ajax({
      method: "POST",
      url: "inc/test.php",
      data: {data: pdf},
    }).done(function(data){
       console.log(data);
    });

PHP: PHP:

if(!empty($_POST['data'])){
$data = base64_decode($_POST['data']);
// print_r($data);
file_put_contents( "../tmp/test.pdf", $data );
} else {
echo "No Data Sent";
}
exit();
var reader = new window.FileReader(); reader.readAsDataURL(doc.output("blob")); reader.onloadend = function () { ... method: 'POST', data: { attachment: reader.result } ... }

JS JS

var pdf =doc.output(); 
    var data = new FormData();
    data.append("data" , pdf);
    var xhr = new XMLHttpRequest();
    xhr.open( 'post', 'inc/test.php', true ); 
    xhr.send(data);

PHP 的PHP

if(!empty($_POST['data'])){
    $data = $_POST['data'];
    $fname = "test.pdf"; 
    $file = fopen("test/pdf/" .$fname, 'r'); 
    fwrite($file, $data);
    fclose($file);
} else {
    echo "No Data Sent";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM