1

I send a file from a client-side to the server-side:

const formData = new FormData();
formData.set("file", file, file.name);

let ip = location.host;

$.ajax({
    processData: false,
    contentType: false,
    type: "POST",
    url: http() + ip + "/fileUpload",
    data: formData,
    success: %callback%,
    error: function (err) {
        return false;
    }
});

The server-side (Node.js) catches this request via Express.js:

app.post("/fileUpload", function (req, res) {…}

Now, I want to access the uploaded file on a server-side in debugger.
Since the file is wrapped with FormData, I try to use req.body.get("file") following the FormData.get() API, and expect to get the file in base64/blob, but instead I get:

Uncaught TypeError: req.body.get is not a function

How can I access an uploaded file, which is wrapped by FormData from a POST-request?

The file is 100% uploaded to the server-side, since multer is capable of serializing the request to the file.

P.S. I've checked already How to send FormData objects with Ajax-requests in jQuery?, but there the answer demonstrates just a way to send a request, not to proceed the request.

Mike
  • 14,010
  • 29
  • 101
  • 161

1 Answers1

-1

I can propose a sort of a workaround. You can access it with multer as described in the tutorial https://www.npmjs.com/package/multer

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

if you prepare the formData object in the following manner:

let formData = new FormData();
formData.set("file",file, file.name);

you shall be able to fetch the file object on the server side with multer as follows:

const upload = multer({ storage: './../uploads/' }).single('file');
upload(req, res, function(err) {
        console.log("The file: " + req.file);
        console.log("The path: " + req.file.path);
});
IgorM
  • 1,348
  • 1
  • 12
  • 28