簡體   English   中英

Node.js 將下載的 pdf 文件的 stream 轉換為 Z95A1446A7120E4AF5C0C8878ABBBE 中的字符串結果

[英]Node.js converting stream of downloaded pdf file to base64 string results in error

在我的應用程序中,我正在從 amazon s3 下載以前存儲的圖像和 pdf 文檔:

public async downloadFile(file: string): Promise<DownloadedFileType> {
    const data = await this.#s3.send(
      new GetObjectCommand({
        Bucket: process.env.AWS_BUCKET_NAME,
        Key: file,
      }),
    );

    return { stream: data.Body, name: file };
  }

當我嘗試將獲得的 stream 轉換為 base64 圖像(將其作為“預覽”發送到我的前端)時,會出現問題:

private getBase64FromStream(
    stream: Readable,
    fileType: string,
  ): Promise<string> {
    return new Promise((resolve, reject) => {
      const data: Uint8Array[] = [];

      function onData(chunk: Uint8Array): void {
        data.push(chunk);
      }

      stream.on('data', onData);
      stream.once('end', () => {
        const result = Buffer.concat(data).toString('base64');
        const mimeType =
          fileType === 'pdf' ? 'application/pdf' : `image/${fileType}`;

        resolve(`data:${mimeType}; base64, ${result}`);

        stream.off('data', onData);
      });
      stream.once('error', reject);
    });
  }

它適用於圖像(jpeg、png 等),但不適用於 pdf 文檔。 在我的前端渲染這樣的 base64 會導致錯誤:

export function PreviewComponent({
  src,
}: IProps): JSX.Element {
  const classes = useStyles();
  const { dispatch } = useContext(AppContext);
  const onImageClick = () => {
    dispatch(openImageModalAction(src));
  };
  const onError = (e: unknown) => {
    console.log(e);
  };

  return (
    <img
      className={classes.imageWrapper}
      src={src}
      alt="preview"
      onClick={onImageClick}
      onError={onError}
    />
  );
}

錯誤是 React 的 SyntheticBaseEvent:

type: "error"
_reactName: "onError"

我不知道我做錯了什么。 我知道您可以將 pdf 文件轉換為 base64。 任何幫助將不勝感激。

您正在使用 <img> 標簽來顯示您的 PDF,但碰巧 PDF 不是圖像,因此 img 標簽將不支持它。

MDN 確認 PDF 不在 img 標簽支持的格式列表中:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img

嘗試使用嵌入或 iframe 標簽代替,如下所示:

如何在 HTML 中顯示 PDF 文件?

請參閱此處的反應示例:

https://stackblitz.com/edit/react-ts-pgvu9y?file=index.tsx

class App extends Component<AppProps, AppState> {
  constructor(props) {
    super(props);
    this.state = {
      name: 'React'
    };
  }

  render() {
    return (
      <div>
          Displaying a PDF file with React<br/>

          embed tag works<br/>
          <embed src="https://www.inkwelleditorial.com/pdfSample.pdf" width="800px" height="400px" />

          img tag does not work<br/>
          <img src="https://www.inkwelleditorial.com/pdfSample.pdf" width="800px" height="400px" />
        
      </div>
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM