1

Is there a way to use formidable without redirection to the /upload path?

As found online and in the docs..

HTML

<form action="/upload" enctype="multipart/form-data" method="post">
   <input type="file" name="file">
   <input type="submit" value="Upload">
</form>

EXPRESS

 var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
  console.log(87987)
  console.log(files)
  console.log(files.file)
    // `file` is the name of the <input> field of type `file`
    var old_path = files.file.path,
        file_size = files.file.size,
        file_ext = files.file.name.split('.').pop(),
        index = old_path.lastIndexOf('/') + 1,
        file_name = old_path.substr(index),
        new_path = path.join(process.env.PWD, 'public/uploads/', file_name + '.' + file_ext);

    fs.readFile(old_path, function(err, data) {
        fs.writeFile(new_path, data, function(err) {
            fs.unlink(old_path, function(err) {
                if (err) {
                    res.status(500);
                    res.json({'success': false});
                } else {
                    res.status(200);
                    res.json({'success': true});
                }
            });
        });
    });
});

The image uploads into the folder but I'm redirected to the /uploads path because of the "action = '/upload'" attribute in the form element.

I would like to stay on the same page, but when I try to change the "action" value, then I'm not able to send the image to the server

abcf
  • 685
  • 2
  • 10
  • 25

1 Answers1

0

use res.redirect or remove the action attribute from the form to post to the current page.

http://expressjs.com/api.html#res.redirect

if you remove the action attribute to post to the current page then you have to add a route to express for that page to process the post request

http://expressjs.com/api.html#app.route

if you have trouble with removing the action attribute then try using action="?" to post to the current page.

Timmerz
  • 6,090
  • 5
  • 36
  • 49
  • I tried removing the action and using $http.post instead but then the files parameter in form.parse returns an empty object. So I'm assuming when I use the action attribute, the action attribute manually populates the files object. I also thought of using res.redirect so I guess I could use req.headers.host + '/path'. I was hoping someone knew of another way unless this is the optimal method. Thanks for your answer, I'm going to wait a while before choosing this – abcf Feb 20 '15 at 02:47
  • `$http.post`? are you using angular? if you need to use ajax to post the form try using `new FormData` as suggested in this post: http://stackoverflow.com/questions/10899384/uploading-both-data-and-files-in-one-form-using-ajax – Timmerz Feb 21 '15 at 18:26