2017-06-18 53 views
2

我用jsPDF生成了一個pdf對象。我想發送帶有AJAX附帶PDF的郵件,但我無法正確發送文件。我嘗試在Blob對象中進行轉換,然後在PHP中嘗試解碼爲base64以便通過郵件發送,但是當我收到郵件時,我會收到沒有擴展名的blob文件。如何通過ajax發送自動生成的pdf文件

1 .-我創建PDF對象:

var pdf = new jsPDF(); // new pdf object 
pdf.text("Table title", 14, 16); // text line 
var elem = $(".tableSample")[0]; // node -> html to pdf 
var res = pdf.autoTableHtmlToJson(elem); // lib to transform htmlTables to pdf 
pdf.autoTable(res.columns, res.data, {startY: 20}); // lib to transform htmlTables to pdf 

var outputBase64 = pdf.output('datauristring'); 
var blob = new Blob([outputBase64], { type: "application/pdf"}); 

2:我打電話給我的函數的Ajax:

ajaxAdjunto({ 
    controler : "ctInformes2.php", 
    method : "enviarInforme", 
    attached : blob, 
    paramValid : { 
     mailText : "This is the mail body", 
     mailAsunto : "Este es el asunto", 
     mailDest : "[email protected]" 
    }, 
    callbackSucces : function (backParam) { }, 
    callbackError : function (err) { } 
}); 

3 .-我的功能阿賈克斯準備發送帶附件與FORMDATA對象:

function ajaxAdjunto(objParam){ 
url = "./controller/"+objParam.controler+"?metodo="+objParam.method; 
param = new FormData(); 
//Add to FormData mail text 
for (var item in objParam.paramValid){ 
    if (item == ""){ 
     param.append(item , "null"); 
    }else{ 
     param.append(item , objParam.paramValid[item ]); 
    } 
}  
//Add to FormData file 
param.append("adjunto", objParam.attached); 
//Call Ajax 
$.ajax({ 
    data: param, 
    type: "POST", 
    url: url, 
    cache: false, 
    contentType: false, 
    processData: false, 
    success: function (backParam) { 
     objParam.callbackSucces(backParam, objParam); 
     }, 
    error: function (xhr){ 
     if (objParam.callbackError){ 
      objParam.callbackError(xhr); 
     }else{ 
      alerta(xhr.statusText); 
      console.log(xhr);   
     } 
    } 
}); 
} 

PHP代碼 - (我刪除其他$主體內容和郵件標題此示例)

// var_dump -> $_FILES['attached'] 
array (size=5) 
    'name' => string 'blob' (length=4) 
    'type' => string 'application/pdf' (length=15) 
    'tmp_name' => string 'C:\Windows\Temp\php9593.tmp' (length=27) 
    'error' => int 0 
    'size' => int 6328 

// PHP CODE 
if (count($_FILES) > 0){ 
    $nameFile = $_FILES['attached ']['name']; 
    $sizeFile = $_FILES['attached ']['size']; 
    $typeFile = $_FILES['attached ']['type']; 
    $tempFile = $_FILES["attached "]["tmp_name"]; 

    $body .= "--=C=T=E=C=\r\n"; // delimiter 
    $body .= "Content-Type: application/octet-stream; "; 
    $body .= "name=" . $nameFile . "\r\n"; 
    $body .= "Content-Transfer-Encoding: base64\r\n"; 
    $body .= "Content-Disposition: attachment; "; 
    $body .= "filename=" . $nameFile . "\r\n"; 
    $body .= "\r\n"; // empty line 

    $fp = fopen($tempFile, "rb"); 
    $file = fread($fp, $sizeFile); 
    $file = chunk_split(base64_encode($file)); 

    $body .= "$file\r\n"; 
    $body .= "\r\n"; // empty line 
} 
    $body .= "--=C=T=E=C=--\r\n"; // delimiter end mail 

//Send mail 
if(mail($mailTo, $subject, $body, $header)){ 
    echo "mail was sent"; 
}else{ 
    echo "error when try send mail"; 
} 
+0

請在您的問題中添加打印:$ _FILES的_r或var_dumo輸出。 – hakre

+0

將其添加到問題中,而不是在評論中。這就是它所在的地方,然後更容易格式化和閱讀。 – hakre

+0

只是我做了,謝謝(第一次) – terribleWeb

回答

0

的解決方案是在第1點:

1º - 添加此功能

function dataURItoBlob(dataURI) { 
    // convert base64/URLEncoded data component to raw binary data held in a string 
    var byteString; 
    if (dataURI.split(',')[0].indexOf('base64') >= 0) 
     byteString = atob(dataURI.split(',')[1]); 
    else 
     byteString = unescape(dataURI.split(',')[1]); 

    // separate out the mime component 
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; 

    // write the bytes of the string to a typed array 
    var ia = new Uint8Array(byteString.length); 
    for (var i = 0; i < byteString.length; i++) { 
     ia[i] = byteString.charCodeAt(i); 
    } 

    return new Blob([ia], {type:mimeString}); 
} 

2º - 在第1點,當我創建PFD我改變了:

var outputBase64 = pdf.output('datauristring'); 
var blob = new Blob([outputBase64], { type: "application/pdf"}); 

此:

var outputBase64 = pdf.output('datauristring'); 
var preBlob = dataURItoBlob(outputBase64); 
var file = new File([preBlob], "namefile.pdf", {type: 'application/pdf'}); 

3º - 請享用!

0

您在此處指定電子郵件附件的文件名:

$body .= "name=" . $nameFile . "\r\n"; 

變量$nameFile包含作爲字符串「blob」提供的上傳文件的名稱。由於它沒有文件名,你可以逐字使用它。

要更改提供更有用的文件名並將其設置在該行中。

在JavaScript中爲表單數據提供一種方法如下Q &資源:"How to give a Blob uploaded as FormData a file name?"

相關問題