尝试将生成的PDF文件从React Js发送到Django-Rest Post请求时,未提交任何文件

问题描述 投票:0回答:2

尝试在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

我想我发错文件但无法解决它的问题,需要建议。谢谢

javascript reactjs django-rest-framework jspdf html2canvas
2个回答
1
投票

你有错误:

'Content-Type': 'application/json'

如果要发送文件,则应使用multipart / form-data


0
投票

为什么要将有效负载转换为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));
};

© www.soinside.com 2019 - 2024. All rights reserved.