从 aws s3 检索对象并在 Next.js 的网页中显示该对象时出错

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

我正在构建一个 chatpdf 应用程序,我想在浏览器上显示 pdf,该 pdf 作为对象存储在我的 s3 存储桶中。当我使用下面的代码时,我无法显示 pdf。我从 s3 int 获取 pdf_url 链接,格式为:

  1. https://myprojectchatpdf.s3.ap-southeast-1.amazonaws.com/uploads/1710527684936hello.pdf

 export default function PDFViewer({pdf_url}: PDFViewerProps){

 return (<iframe src={`https://docs.google.com/gview?url=${pdf_url}pdf&embedded=true`} className='w-full h-full'></iframe>);
 }```

But on generating the link of the object from the aws console: presigned_link and using the following code i am able to display the pdf but the link would expire after certain amount of time:


```type PDFViewerProps = {pdf_url: string}
export default function PDFViewer({ pdf_url }: PDFViewerProps) {
    var presigned_url = encodeURIComponent('here pasting the presigned_url...');
    const iframeurl = `https://docs.google.com/gview?url=${presigned_url}&embedded=true`;
    console.log('iframe url: ',iframeurl);
    return <iframe src={iframeurl} title = 'pdf-viewer' className=" w-full h-full"></iframe>;
  }```




Please suggest a method by which i can display the pdf of aws object not using presigned_link , using the 1st link method in react-native or next.js.
reactjs amazon-web-services amazon-s3 next.js iframe
1个回答
0
投票

实现此目的的一种方法是将文件(在您的情况下为 PDF)从后端流式传输到客户端。您可以将其存储在临时 ObjectURL 中(只要您的浏览器会话打开,该 URL 就有效)。

next.js 例如

  const response = await fetch('/pdf');
  const blob = await response.blob();
  const url = URL.createObjectURL(blob);
  
  // Open the PDF in a new tab
  window.open(url, '_blank');
© www.soinside.com 2019 - 2024. All rights reserved.