Sending html2pdf generated pdf back to the server

Viewed 2085

I have to send a PDF generated on the client side using the html2pdf to a server. I have managed to convert the generated PDF to base64 and want to send it back using axios. Here is my client side code:

  function myFunction(){
           var element = document.getElementById('element-to-print');
           html2pdf().from(element).outputPdf().then(function(pdf) {
    //Convert to base 64
            const newpdf=btoa(pdf);
            console.log(newpdf)
            var formData = new FormData();
            formData.append("uploadedFile", newpdf);
            axios.post('/upload',formData).then(res => { console.log(res) }).catch(error => {
            console.log(error.response)
        })
    });

Here is my server side code:

app.post('/upload', fileUpload(), function(req, res) {  
  const sampleFile = req.files.uploadedFile;
  // do something with file
  res.send('File uploaded');
})

I think the problem is in client side as I get the base64 version of my converted pdf on my console but after that I get the error:

POST http://localhost:3000/upload 500 (Internal Server Error)

How do I solve this problem? Thanks.

1 Answers

For the FormData in express you should use a middleware such Multer

and you code will be like this :

var express = require('express')
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

var app = express()

app.post('/upload', upload.single('uploadedFile'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
})
Related