【问题标题】:how can i upload react-pdf/renderer displayed pdf to aws s3 storage and download that pdf using s3 link我如何将 react-pdf/renderer 显示的 pdf 上传到 aws s3 存储并使用 s3 链接下载该 pdf
【发布时间】:2022-11-05 22:42:50
【问题描述】:

大家好,我正在使用 react-pdf/renderer react pdf 在我的 react 应用程序上渲染 pdf,现在我想将该渲染的 pdf 直接上传到 aws s3 存储我已经成功制作了一个 api 来将文件上传到 s3 存储,并且它在邮递员中工作正常。我可以使用输入类型文件将文件上传到 s3,但我想将渲染的 pdf 直接上传到该存储,以便以后在我的应用程序中检索。共享锅炉 react-pdf 模板我找到了一些解决方案,例如将 react-pdf 转换为缓冲区和流,但我没有得到任何足够的资源或解决方案。

import React from 'react';
import { Page, Text, View, Document, StyleSheet } from '@react-pdf/renderer';

// Create styles
const styles = StyleSheet.create({
  page: {
    flexDirection: 'row',
    backgroundColor: '#E4E4E4'
  },
  section: {
    margin: 10,
    padding: 10,
    flexGrow: 1
  }
});

// Create Document Component
const MyDocument = () => (
  <Document>
    <Page size="A4" style={styles.page}>
      <View style={styles.section}>
        <Text>Section #1</Text>
      </View>
      <View style={styles.section}>
        <Text>Section #2</Text>
      </View>
    </Page>
  </Document>
);

后端代码

const aws = require('aws-sdk')
const multer = require('multer')
const multerS3 = require('multer-s3');


aws.config.update({
    secretAccessKey: process.env.ACCESS_SECRET,
    accessKeyId: process.env.ACCESS_KEY,
    region: process.env.REGION,

});
const BUCKET = process.env.BUCKET
const s3 = new aws.S3();

const upload = multer({
  storage: multerS3({
      s3: s3,
      acl: "public-read",
      bucket: BUCKET,
      key: function (req, file, cb) {
          console.log(file);
          cb(null, file.originalname)
      }
  })
})

app.post('/uploadContractTos3', upload.single('file'), async function (req, res, next) {

  res.send({s3fileurl : req.file.location})
  // res.send("S3 uploaded")

})

【问题讨论】:

    标签: reactjs amazon-web-services amazon-s3 react-pdf


    【解决方案1】:

    使用来自@react-pdf/renderer 的 renderToStream() 方法:

    const pdfStream = await ReactPDF.renderToStream(<MyPdf />)
    
    var uploadParams = {Bucket: '<bucket>', Key: '<fileName>', Body: pdfStream, ContentType: 'application/pdf'}
    let uploadPromise = await s3.upload(uploadParams).promise()
    console.log('Uploaded file URL', uploadPromise.Location)
    

    第二种方法并不理想,但您可以将文档保存到文件夹,然后再次上传到 S3 存储桶。

    import ReactPDF from "@react-pdf/renderer";
    ReactPDF.render(<MyDocument />, `${__dirname}/example.pdf`);
    

    注意:我不确定 React 但在 NextJS 中,无法通过直接链接在运行时访问动态生成的文件,但您可以参考文件路径。

    【讨论】:

      猜你喜欢
      • 2022-07-29
      • 2020-10-17
      • 2018-08-27
      • 2018-08-31
      • 2018-08-13
      • 1970-01-01
      • 2020-07-01
      • 2022-06-10
      • 2016-05-09
      相关资源
      最近更新 更多