尝试在react js中生成pdf文件,然后将其发送到django rest后端。
我已经使用jsPDF和html2canvas成功创建了pdf文件,但现在无法发送到其余的api,每当我提交它时都会回复“没有提交文件”。我检查了django-rest api并且工作正常,pdf是不会去其余的api。这是我的下面的代码:
genPDF=(evt)=>{
evt.preventDefault();
html2canvas(document.getElementById("pdfid")).then(canvas=>{
let img=canvas.toDataURL('img/png');
let doc=new JsPDF();
doc.addImage(img,'JPEG',30,30);
//doc.save('test.pdf');
let file=doc;
const formdata=new FormData();
formdata.append("file",file);
this.postpdf(formdata)
});
};
postpdf=(payload)=>{
fetch(`http://127.0.0.1:8000/chauffeur/pdf_upload/`,
{
method: 'POST',
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json'
}
}
).then(response => response.json()).catch(error => console.error('Error:', error));
};
请求标题
Content-Type: multipart/form-data; boundary=----
WebKitFormBoundaryEueEwtpzbquHU6Tb
Origin: http://localhost:3000
Referer: http://localhost:3000/contractinvoice
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/73.0.3683.86 Safari/537.36
响应标题
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:3000
Allow: GET, POST, HEAD, OPTIONS
Content-Length: 76
Content-Type: application/json
Date: Wed, 10 Apr 2019 05:44:49 GMT
Server: WSGIServer/0.2 CPython/3.5.2
Vary: Accept, Cookie, Origin
X-Frame-Options: SAMEORIGIN
我想我发错文件但无法解决它的问题,需要建议。谢谢
你有错误:
'Content-Type': 'application/json'
如果要发送文件,则应使用multipart / form-data
为什么要将有效负载转换为JSON.stringify()...有效负载不是json ...试试这个......
postpdf=(payload)=>{
fetch(`http://127.0.0.1:8000/chauffeur/pdf_upload/`,
{
method: 'POST',
body: payload,
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(response => response.json()).catch(error => console.error('Error:', error));
};