0

I have an application that uploads PDF file and then the file has to be converted into Binary (in the backend without saving the file in a temp folder) to store it in a database.

I am being able to upload the file and read the data, however, I am not being able to convert it to binary.

Following is myapp.js

var upload = require("express-fileupload");
app.use(upload());
function upload_file(req, res, next) {
    console.log('here');
    if (!req.files) {
        res.send({
            status: false,
            message: 'No file uploaded'
        });
    }else if (req.method == "POST") {
        console.log('here');
        var form = new formidable.IncomingForm();
        console.log(form);
        let file = req.files.fileToUpload;
        console.log(file);
        }
    }

The output of the function once a pdf file has been uploaded is: enter image description here

I tried const encoded = req.files.fileToUpload.buffer.toString('base64'); and I get an error. I also tried fs.readFileSync but since I'm not storing the file locally, it throws an error.

RRg
  • 123
  • 1
  • 12

1 Answers1

0

According to the docs, req.files.fileToUpload.data should contain the file's data in a buffer:

req.files.foo.data: A buffer representation of your file, returns empty buffer in case useTempFiles option was set to true.

So you should be able to use data and further process this buffer.

eol
  • 23,236
  • 5
  • 46
  • 64
  • I tried ```req.files.fileToUpload.data``` and I'm able to extract the data, but I'm still not being able to convert it to binary – RRg Oct 08 '20 at 14:31
  • Not sure I understand correcty - the buffer already contains the raw bytes? – eol Oct 08 '20 at 15:06
  • Or are you talking about converting it to `base64` as you tried? Then the title of the question would be misleading :) – eol Oct 08 '20 at 15:10
  • I'm getting the data in bytes and I want to convert it to ```binary```. – RRg Oct 08 '20 at 15:38
  • You may want to check out this then: https://stackoverflow.com/a/42847603/3761628 Although you should not need to create a new binary-buffer as you already have the buffer. – eol Oct 08 '20 at 15:57