我用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";
}
請在您的問題中添加打印:$ _FILES的_r或var_dumo輸出。 – hakre
將其添加到問題中,而不是在評論中。這就是它所在的地方,然後更容易格式化和閱讀。 – hakre
只是我做了,謝謝(第一次) – terribleWeb