简体   繁体   中英

How to open a pdf file in browser instead of downloading it?

I have an api which provides a json-object with a link to the pdf

{ pdf_link: 'http://localhost:3000/logs.pdf' }

When user clicks on the file name, I want to open this pdf in a separate browser tab.

I tried giving the url as href in an a tag

<a href={response.pdf_link} target='_blank'>{FileName}</a>

But when I click on the link, pdf is getting downloaded, not opening in a browser tab.

I found this blog post and tried the following.

import axios from 'axios';
import React from 'react';

export const PdfLink = ({ apiResponse }: any) => {

  const showFile = (blob: Blob, fileName: string) => {
    const newBlob = new Blob([blob], {type: 'application/pdf'});

    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(newBlob);
      return;
    }

    const data = window.URL.createObjectURL(newBlob);
    const link = document.createElement('a');
    link.href = data;
    link.download = fileName;
    link.click();

    setTimeout(() => {
      window.URL.revokeObjectURL(data);
    }, 100);
  };

  const onClickLink = () => {
    axios({
      method: 'GET',
      responseType: 'blob',
      url: apiResponse.pdf_link,
    })
    .then(r => showFile(r.data, apiResponse.fileName));
  };

  return (
    <span className='link' onClick={onClickLink}>
      file.pdf
    </span>
  );
};

But this is failing at the api call to get the file blob.

axios({
      method: 'GET',
      responseType: 'blob',
      url: apiResponse.pdf_link,
    })

Error: Access to XMLHttpRequest at 'http://localhost:3005/file.pdf' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The below image shows the request and response headers of the api call

在此处输入图像描述

I know that the above error is due to cors but in the server, I am allowing requests from other origins as well

app.use(KoaCors({ origin: '*', credentials: true }));

What am I doing wrong?

You can use the object tag to display the pdf:-

<object
        data={/* url of your pdf file*/}
        type="application/pdf"
        width="100%"
        height="100%"
></object>

For more info, look here https://www.w3schools.com/tags/tag_object.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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