2017-03-16 99 views
0

我有一個問題,發送pdf附加電子郵件使用jspdf與ajax和Django。問題是服務器端views.py 打印(pdf_s)總是反彈'無'但客戶端console.log(pdf)返回二進制值。發送PDF附加電子郵件使用jsPDF ajax和Django python

請參考我試過的下面的代碼。

的script.js

這是客戶端的代碼。和我使用Ajax來通過瀏覽器開發者工具將數據發送到服務器

function sendMail(){ 
    getCanvas().then(function(canvas) { 
     console.log('Test'); 
     var img = canvas.toDataURL("image/png",0.98); 
     var imgWidth = 200; 
     var pageHeight = 295; 
     var imgHeight = canvas.height * imgWidth/canvas.width; 
     var heightLeft = imgHeight; 

     var doc = new jsPDF('p', 'mm', 'a4', 'pt'); 
     var position = 0; 

     doc.addImage(img, 'JPEG', 5, position, imgWidth, imgHeight); 
     heightLeft -= pageHeight; 

     while (heightLeft >= 0) { 
      position = heightLeft - imgHeight; 
      doc.addPage(); 
      doc.addImage(img, 'JPEG', 5, position, imgWidth, imgHeight); 
      heightLeft -= pageHeight; 
     } 
     var pdf = btoa(doc.output()); 
     console.log(pdf); 
     $.ajax({ 
      type:'POST', 
      url:'sendmail/', 
      data:{ 
       pdf_data: pdf, 
       csrfmiddlewaretoken: csrftoken 
      }, 
      success:function(data){ 
       console.log(data); 
      } 

     }); 
    }); 
} 

views.py

def SendMail(request,scan_id): 

    pdf_s = request.GET.get('pdf_data') 
    print(pdf_s) 
    fo = open('test.pdf','w') 
    fo.write(pdf_s) 
    fo.close() 

    html_content = "Test Message" 
    email = EmailMessage("test", html_content, "test", ["[email protected]"]) 
    email.content_subtype = "html" 

    fd = open('test.pdf', 'r') 
    email.attach('test', fd.read(), 'application/pdf') 

    res = email.send() 
    if res: 
     status = 'Success' 
    else: 
     status = 'Fail' 
    return HttpResponse(status) 

回答

0

檢查Ajax請求>網絡。也許「pdf_data」參數不存在。

我通過原生js發送文件。

JS

var formData = new FormData(); 
formData.append('file.pdf', file); 
var xhr = new XMLHttpRequest(); 
xhr.onload = function (e) { 
    if (xhr.readyState === 4 && xhr.status === 200){ 
     result=xhr.responseText; 
     console.log(result); 
    } 
} 
xhr.open('POST', url, true); 
xhr.setRequestHeader("X-CSRFToken", csrfmiddlewaretoken); 
xhr.send(formData); 

的Python

element_file=File(request.FILES[request.FILES.keys()[0]]) 
with open('file.pdf','wb+') as destination: 
    for chunk in element_file.chunks(): destination.write(chunk) 

它在工作的情況下,如果通過輸入類型= 「文件」 從本地計算機發送文件