在没有输入字段的情况下将本地图像文件上传到AWS S3

时间:2019-07-01 18:28:58

标签: reactjs image pdf amazon-s3 file-upload

我正在制作一个React应用,我可以让用户上传pdf文件,然后将pdf文件转换为jpg文件,将其存储在本地,然后将其上传到AWS s3。但是当前,当我将jpg文件上传到aws s3时,该文件未作为图像文件上传。我想将本地图像文件上传到AWS s3,而不必使用<input type="file" />

我尝试将fs.readFile()s3.upload()一起使用,但是上传的文件不是图像文件。我也尝试使用multer-s3,但这需要用户使用<input type="file" />手动选择图像文件,这是我要避免的。

这是我上载jpg文件的方式:

const aws = require("aws-sdk");
const multer = require("multer");
const fs = require("fs");
const convertPdf = require("pdf-poppler");
const s3 =  new aws.S3({
  accessKeyId: "<key>",
  secretAccessKey: "<secret>",
  Bucket: "<bucketName>"
});
const storage = multer.diskStorage({ 
  destination: function(req, file, cb) {
    cb(null, path.join(__dirname + "/uploads/"));
  },
  filename: function(req, file, cb) {
    // let pdfName = "samplePDF";
    // req.body.file = pdfName;
    cb(null, file.originalname);
  }
});

const upload = multer({
  storage: storage
});  //SAVING PDF TO DISK STORAGE

router.post("/pdf", upload.single("pdf"),(req, res, next) => {
  const uploadPath = req.file.path;
  var imagePath = req.file.destination + req.file.originalname.slice(0, -4) + "-1.jpg";
  let opts = {
    format: "jpg",
    out_dir: req.file.destination,
    out_prefix: path.basename(req.file.path).slice(0, -4),
    page: null
  }
  //CONVERTING PDF TO JPG
  convertPdf.convert(uploadPath, opts).then(() => 
  {
     fs.readFile(imagePath, (err, data) => { 
      if (err) throw err;// UPLOADING FILE BUT NOT IN IMAGE FORMAT
      const params = {
         Bucket: "<bucketName>",
         Key: path.basename(imagePath),
         Body: data 
       };
      s3.upload(params, (s3Error, data) => {
        if (s3Error) throw s3Error;
        console.log(`File uploaded successfully at ${data.Location}`);
        res.json({
          image: data.key,
          location: data.Location
        });
      });
     });
    });
  });

我期望要上载图像文件,但不是上载文件不是图像文件,这是问题所在。有什么方法可以在不使用输入字段的情况下将本地图像文件上传到AWS s3?

编辑:结果表明,aws s3默认情况下将上传的文件设为私有,这就是为什么无法读取文件的原因,当我将文件设为公开时,问题已解决。

1 个答案:

答案 0 :(得分:0)

上载的文件是图像文件,只是没有正确的权限。我添加了ACL: "public-read"参数,现在文件按预期显示。 更新的代码:

  fs.readFile(imagePath, (err, data) => {
      if (err) throw err;
      const params = {
        Bucket: "flyingfishcattle",
        Key: path.basename(imagePath),
        Body: data,
        ACL: "public-read" 
      };
      s3.upload(params, (s3Error, data) => {
        if (s3Error) throw s3Error;
        console.log(`File uploaded successfully at ${data.Location}`);
        res.json({
          image: data.key,
          location: data.Location
        });
      });
    });