通过Ajax将PdfByte数组从JS发送到php,并通过php-File发送电子邮件

问题描述 投票:1回答:1

我有以下问题。

我使用js的pdf-lib库创建pdf。最后一步,我创建一个uint8array:

const pdfBytes = await pdfDoc.save()

现在,我想借助ajax将这个pdfbytes发送到Web服务器上的php.file。此php文件应从pdf字节数组中创建一个pdf,并将其附加到电子邮件中,然后将其发送到特定的电子邮件地址。

我这样编码了ajax调用:

 function sendWithAjax(pdfBytes, email) {
        if (window.XMLHttpRequest) {
            // AJAX nutzen mit IE7+, Chrome, Firefox, Safari, Opera
                xmlhttp=new XMLHttpRequest();
            }
        else {
            // AJAX mit IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.open("POST", "sendContractEmail.php", true);
        const data = {bytes: pdfBytes, mail: email};
        xmlhttp.send(data);

    }

但是我如何编码php.file生成pdf并通过电子邮件发送呢?

我的PHP代码:

<?php

if($_SERVER['REQUEST_METHOD'] == 'PUT') {
    echo "this is a put request\";
    parse_str(file_get_contents("php://input"),$post_vars);

    echo $post_vars['pdfBytes']." is pdfBytes\";

?>

感谢您的帮助!

javascript php ajax pdf email-attachments
1个回答
0
投票

我为同一个问题奋战了一周。最后我得到了结果。

第一个问题是将TypedArray缓冲区(pdfBytes)转换为Base64

var data = new Uint8Array(pdfBytes);

var base64 = bufferToBase64(data); // cal function that convert TypedArray Buffer

// console.log(base64);检查输出

var formData = new FormData();

   formData.append("name", name);
   formData.append("surname", surname); 
   formData.append("email", email);
   formData.append("pdffile", base64);

   var request = new XMLHttpRequest();
   request.open("POST", "test.php");
   request.send(formData);

发送到php

    $first_name = $_POST['name']; // required
    $last_name = $_POST['surname']; // required
    $email_to = $_POST['email']; // required
    $binarr=$_POST['pdffile'];
    $email_from = '[email protected]';
    $extension = 'pdf';

    $FileName = str_replace("'", "_", $first_name);
    $FileSurName = str_replace("'", "_", $last_name);

    $filePath = $_SERVER['DOCUMENT_ROOT'].'/files/'.$FileName."_".$FileSurName.".".$extension;

    # Decode the Base64 string, making sure that it contains only valid characters
    $bin = base64_decode($binarr, true);

在此处检查您的$ bin base64guru

    if (strpos($bin, '%PDF') !== 0) {
    throw new Exception('Missing the PDF file signature');
    }

    # Write the PDF contents to a local file
    file_put_contents($filePath, $bin); // Goal!

享受轻松的生活

© www.soinside.com 2019 - 2024. All rights reserved.