从 api 响应获取 pdf 文件

我正在调用 api 并获取 pdf 作为回报。


fetch(`api` + guid, {

   method: "GET",

   headers: {

    "Accept": "application/octet-stream",

    "Authorization": "Bearer " + token,

   },

   responseType: 'arraybuffer',

})

.then((res) => res.text())

.then((data) => {

    fs.writeFileSync('file.pdf', data);

});

我收到了 pdf 文件,但问题是 pdf 文件始终为空。但是当我接受 json 响应时,它工作正常。


我发现了类似的问题,但没有一个解决方案对我有用。


如果有人能指出这个问题那就太好了。


摇曳的蔷薇
浏览 131回答 4
4回答

阿波罗的战车

我发现了这个问题。因为我使用的是 fetch 而不是 Axios。我们无法将responseType 作为 Fetch 的选项传递。fetch(`api` + guid, {   method: "GET",   headers: {    "Accept": "application/octet-stream",    "Authorization": "Bearer " + token,   },   // responseType: 'arraybuffer' //#1 remove this,})相反,响应本身可以作为数组缓冲区传递,如下所示。.then((res) => res.arraybuffer())代替.then((res) => res.text())现在不要直接使用响应来编写我们的 pdf 文件。我们可以将数据更改为 base64 字符串,然后再次将其解码以创建 pdf 文件。我使用base64ToPdf npm 包来处理这个问题。.then(data => {  var base64Str = Buffer.from(data).toString('base64');  base64.base64Decode(base64Str, "file.pdf");})我希望这对其他人有帮助。:)

梵蒂冈之花

    Change res.arraybuffer() to  res.arrayBuffer()Below is the working code with webdriverio-  var headers = {            Authorization: "Bearer " + accessToken,            Accept: 'application/pdf'        }                  fetch(                apiurl,                {                    headers: {                        Accept: "application/octet-stream",                        Authorization: "Bearer " + accessToken                    },                },            )                .then((res) => {                    if (!res.ok) {                        return res.status.toString()                    }                    return res.arrayBuffer()                })                .then((data) => {                    var base64Str = Buffer.from(data).toString('base64');                    base64.base64Decode(base64Str, filename);                })                .catch(                    (err) => {                        return err.Message;                    })

元芳怎么了

这是对我有用的示例:async createPdf(context, data) {&nbsp; &nbsp; let url = new URL(baseURL + '/invoice/createPdf');&nbsp; &nbsp; url.search = new URLSearchParams({&nbsp; &nbsp; &nbsp; &nbsp; id: data&nbsp; &nbsp; })&nbsp; &nbsp; await fetch(url, {&nbsp; &nbsp; &nbsp; &nbsp; method: 'GET',&nbsp; &nbsp; &nbsp; &nbsp; headers: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'Authorization': "Bearer " + localStorage.getItem("jwt"),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'Accept': 'application/octet-stream'&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; }).then((res) => res.arrayBuffer())&nbsp; &nbsp; &nbsp; &nbsp; .then(data => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var base64Str = Buffer.from(data).toString('base64');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var binaryString = window.atob(base64Str);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var binaryLen = binaryString.length;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var bytes = new Uint8Array(binaryLen);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (var i = 0; i < binaryLen; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var ascii = binaryString.charCodeAt(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; bytes[i] = ascii;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var arrBuffer = bytes;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var newBlob = new Blob([arrBuffer], { type: "application/pdf" });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (window.navigator && window.navigator.msSaveOrOpenBlob) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; window.navigator.msSaveOrOpenBlob(newBlob);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data = window.URL.createObjectURL(newBlob);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var link = document.createElement('a');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.body.appendChild(link);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; link.href = data;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; link.download = "Faktura.pdf";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; link.click();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; window.URL.revokeObjectURL(data);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; link.remove();&nbsp; &nbsp; &nbsp; &nbsp; })

www说

就我而言,响应与您的相同,我正在尝试将其转换为 pdf 文件,以便我可以在 UI 上预览它。为此,我需要获取响应中已存在的 blob 类型的 URL...以获取我所做的 URLURL.createObjectURL(myblob)const [url,seturl] = useState('');response&nbsp; .then((resp) => resp.blob())&nbsp; .then((myBlob) => {&nbsp; &nbsp; seturl(URL.createObjectURL(myBlob)); //<-- use this for fetching url from your response&nbsp; &nbsp; console.log(myBlob);&nbsp; })&nbsp; .catch((err) => {&nbsp; &nbsp; console.log(err.message());&nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript