Upload file using NodeJS and node-formidable
Asked Answered
J

2

12

I succeed uploading file using node.js and the formidable module yet, the file that got save on the disk is in some kind of a bad format ( bad encoding) e.g. if I upload an image I can't view it, if I upload a txt file gedit provide the following msg: "gedit has not been able to detect the character encoding. Please check that you are not trying to open a binary file. Select a character encoding from the menu and try again."

here is the code:

form.encoding = 'utf-8';
form.parse(req, function(err, fields, files) {
    fs.writeFile('test.js', files.upload,'utf8', function (err) {
          if (err) throw err;
          console.log('It\'s saved!');
    });
});
Juta answered 3/4, 2011 at 15:46 Comment(0)
W
20

The problem is the that files.upload is not the content of the file, it is an instance of the File class from node-formidable.

Look at:

https://github.com/felixge/node-formidable/blob/master/lib/file.js

Instead of trying to write the file to disk again, you can just access the path to uploaded file like this and use fs.rename() to move it where you want:

fs.rename(files.upload.path, 'yournewfilename', function (err) { throw err; });
Wace answered 15/6, 2011 at 23:24 Comment(1)
what is fs. I don't see any where it definedRibbonfish
B
4

Is the form set to enctype="multipart/form-data"?

I've only used formidable with Express - the Express example works fine:

https://github.com/visionmedia/express/tree/master/examples/multipart

Brachylogy answered 4/4, 2011 at 20:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.