13

I am using the jQuery Form Plugin and multer to upload files to my server. This works just fine, but I am trying to pass an additional parameter, which will determine where exactly the file will be saved.

I have following code, which I would like to extend to behave as stated:

HTML

<form id="uploadForm"
      enctype="multipart/form-data"
      action="/files"
      method="post">
    <input type="file" id="userFile" name="userFile"/>
    <input type="text" hidden id="savePath" name="savePath" value="path"/>
</form>

Client JS

uploadForm.submit(function() {
    $(this).ajaxSubmit({

        error: function(xhr) {
            console.log('Error: ' + xhr.status);
        },

        success: function(response) {
            console.log('Success: ' + response);
        }
    });

    return false;
});

Node.js Route

app.post(APIpath + "file",function(req,res){
    var storage = multer.diskStorage({
        destination: absoluteServePath+ "/" + config.filePath,
        filename: function (req, file, cb) {
            cb(null, file.originalname);
        }
    });
    var upload = multer({ storage : storage}).any();

    upload(req,res,function(err) {
        if(err) {
            console.log(err);
            return res.end("Error uploading file.");
        }
        res.end("File has been uploaded");
    });
});

Note: I know I am not checking for mimetypes or sanitizing the user files, but it is mainly secondary for me right now.

Shibbir Ahmed
  • 1,350
  • 13
  • 19
Clemens Himmer
  • 1,340
  • 2
  • 13
  • 26

1 Answers1

32

The problem is that multer that saves files first, and only then writes to req the remaining part of the form - such as hidden fields.

Try this:

app.post(APIpath + "file",function(req,res){
    var storage = multer.diskStorage({
        destination: tmpUploadsPath
    });
    var upload = multer({ storage : storage}).any();

    upload(req,res,function(err) {
        if(err) {
            console.log(err);
            return res.end("Error uploading file.");
        } else {
           console.log(req.body);
           req.files.forEach( function(f) {
             console.log(f);
             // and move file to final destination...
           });
           res.end("File has been uploaded");
        }
    });
});
stdob--
  • 28,222
  • 5
  • 58
  • 73
  • Hi. Please assist be adding an example for moving to final destination. For my case i want to move a cloud location @stdob-- – O'Dane Brissett Sep 18 '19 at 01:41
  • 1
    I can't access the body values appended after file. So I appended file at last. – Ataberk May 03 '20 at 16:38
  • Thank you very much for this! Helped me out so much! I had to use req.file to get what I needed, so if the above doesn't work for you, just log the body to see if what you need is in there. – DORRITO Sep 24 '20 at 05:16