【发布时间】:2017-03-16 13:42:52
【问题描述】:
我在使用带有 ajax 和 django 的 jspdf 发送 pdf 附件电子邮件时遇到问题。问题是服务器端 views.py print(pdf_s) 总是重新运行 'None' 但客户端 console.log(pdf) 返回二进制值.
请参考下面我试过的代码。
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", ["test@test.com"])
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)
【问题讨论】:
标签: python ajax django pdf jspdf