繁体   English   中英

pdf文件无法在浏览器中打开

[英]pdf file not opening in browser

我正在从node.js后端接收pdf文件作为api调用响应。该文件在浏览器窗口中以编码格式打开。我尝试下载但下载的文件打开错误(错误:无法加载pdf文档)我被告知响应主体是base64编码的。

是他们可以正确打开/下载pdf的任何方式吗?我正在使用react.js,它是新的。

代码段:

从'js-file-download'导入FileDownload;

export function getTaxInvoice({token}){
  const authString = `Bearer ${token}`;

  return (dispatch) => {
    return axios.get(`${MAIN_URL}/rental_invoice`,{
      headers: {Authorization: authString, 'Accept': 'application/json','Content-Type': 'application/pdf'},
      responseType: "arraybuffer",//I have tried with blob as well
      encoding: null
      })
    .then((response)=>{
      FileDownload(response, 'some.pdf');
      const taxInvoiceUrl = window.URL.createObjectURL(new Blob([response.data]));
      window.open(taxInvoiceUrl, "_blank");
      console.log( response); 
      // dispatch(taxInvoiceLoadSuccess(taxInvoiceUrl));
      // dispatch(onViewChanged("rental_invoice"));
    }) 
    .catch((error)=>{
      dispatch(taxInvoiceLoadFailed());
    })
  }
}

api调用的响应: 图片片段

尝试改变
FileDownload(response, 'some.pdf');

FileDownload(response.data, 'some.pdf');

这是我过去用来执行此操作的一些代码示例:

function downloadURI (url, name) {
  var link = document.createElement('a')
  link.download = name
  link.href = url
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

export function download (url, type = 'application/pdf', name = 'example') {
  get(url, (err, result) => {
    if (err) return handleError(err)
    const blob = new Blob([result.body], { type })
    const downloadUrl = URL.createObjectURL(blob)
    downloadURI(downloadUrl, name)
  })
}

它将下载文件并创建一个对象URL,并通过以编程方式单击链接自动触发打开文件。

终于解决了这个问题(我的高级开发人员帮助了我)。最终代码如下:在npm上安装base64js和filedownload。

export function getTaxInvoice({token}){
  const authString = `Bearer ${token}`;

  return (dispatch) => {
    return axios.get(`${MAIN_URL}/rental_invoice`,{
      headers: {Authorization: authString, 'Accept': 'application/pdf','Content-Type': 'application/pdf'}
      })
    .then((response)=>{
      FileDownload(base64js.toByteArray(response.data), 'some.pdf');
      const taxInvoiceUrl = window.URL.createObjectURL(new Blob([base64js.toByteArray(response.data)], { type: "application/pdf" }) );
      window.open(taxInvoiceUrl, "_blank");
      dispatch(taxInvoiceLoadSuccess(response.data));
      dispatch(onViewChanged("rental_invoice"));
    }) 
    .catch((error)=>{
      console.log(error);
      dispatch(taxInvoiceLoadFailed());
    })
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM