6

I want to download a pdf file using a form, then extract the first page and convert to jpeg (using PDFImage), then upload both the original pdf and the jpeg to my s3 bucket. The code for individual steps is fine but I cant work out how to do the jpeg conversion before using multers3 to upload. The code is as follows:

Form

<form action="/pdfCreate/<%= paper.id %>?_method=PUT" method="POST" enctype="multipart/form-data">
    <div class="uploadForm">
        <label for="pdfUpload">Select file to upload</label>
        <input type="file" id="pdfUpload" class="uploadfile" name="file" id="file-Upload" placeholder="Upload pdf file">
    </div>
    <div class="uploadForm">
        <button type="submit" value="Upload PDF">Upload Paper Info</button>
    </div>
</form>

Route

router.put("/pdfCreate/:id", upload.single("file"), (req,res) => {
    const pdfFile = req.file;
    const pdfPath = req.file.location;
        PDFfile.updateOne ({_id:req.params.id}, {pdfPath:pdfPath}, function(err,file){
            if(err){
                console.log("Error");
            } else {
                // req.flash("success", "PDF successfully uploaded");
                res.render("displayPage", {path: pdfPath});
            }
        });
    }
);

File upload

aws.config.update({
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    region: 'us-east-2',
});

const s3 = new aws.S3();

const upload = multer({
  storage: multerS3({
    acl: 'public-read',
    s3:s3,
    bucket: process.env.S3_BUCKET,
    metadata: function (req, file, cb) {

      cb(null, {fieldName: file.fieldname});
    },
    key: function (req, file, cb) {
      const fileName = Date.now().toString() + "-" + file.originalname;
      cb(null, fileName);
    }
  })
});

The PDF to JPEG Image convert should work like the following code taking in a file name "file.pdf". What I would like to do is to take the file that is submitted to the route (req.file?) and use that instead but I get an error saying that is an object not a string.

let pdfImage = new PDFImage("./public/file.pdf", {convertOptions: {"-resize" : "300%",}
    });
    pdfImage.convertPage(0).then(function (imagePath) {
    fs.existsSync("/tmp/slide-0.png") 
    });

So the problem is firstly using the file that is sent to the route so I can implement the PDFImage conversion THEN send both the original PDF and new JPEG to multer (e.g upload.array(). I was thinking maybe I could use the multer middleware as I currently have it, do the conversion then send that file but really cant work out how to put that all together. Any help appreciated!

dougfair
  • 348
  • 1
  • 3
  • 12

0 Answers0