1

I am attempting to upload particular photos in reference to a client's folder in my public/assets directory. The file path should be public/assets/:id. However, from my code, when it is ran the file path always is returned as public/assets/undefined. Does anyone have suggestions as to how to fix this ? Here is the code in express.

app.param('id', function (req, res, next, id) {
 console.log(req.params.id);
  next();
  });
app.post('/file-upload', function(req, res) {
  // get the temporary location of the file
 var tmp_path = req.files.thumbnail.path;
  // set where the file should actually exists - in this case it is in the "images" directory
 var target_path = './public/assets/'+req.params.id;
  // move the file from the temporary location to the intended location
 fs.rename(tmp_path, target_path, function(err) {
    if (err) throw err;
    // delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files
    fs.unlink(tmp_path, function() {
        if (err) throw err;
        res.send('File uploaded to: ' + target_path + ' - ' + req.files.thumbnail.size + ' bytes');
     });
  });
});
1
  • There are no params in the path /file-upload, so req.params.id will indeed be undefined. You can achieve what you want by POSTing the id in a hidden field or sending it in a cookie. Commented Jun 20, 2016 at 17:35

2 Answers 2

2

In routing you are not passing your parameter , please check and change your route logic like this

app.post('/file-upload/:id', function(req, res) {

 var target_path = './public/assets/'+req.params.id; //or use req.param('id')

  ................

});

Post link pass your second segment is your id example : http://localhost:port/file-upload/123

If you facing problem please use Passing variables as query string using '?' operator

  app.post('/file-upload', function(req, res) {

     var target_path = './public/assets/'+req.query.id; 

      ................

    });

Post link your like this example : http://localhost:port/file-upload?id=123

Sign up to request clarification or add additional context in comments.

Comments

0

You can use :id in the first argument of .post like:

app.post('/file-upload/:id', function(req, res) {

and then retrieve like you are doing in the code with req.params.id.

In the HTML you should change the action path according to the id you want to pass.

1 Comment

When I put <form method="post" action="/file-upload/{{client.id}}"> I get an error that says [$interpolate:noconcat]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.