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!');
    });
});
4

2 回答 2

20

问题是 files.upload 不是文件的内容,它是来自 node-formidable 的 File 类的实例。

看着:

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

无需再次尝试将文件写入磁盘,您可以像这样访问上传文件的路径并使用 fs.rename() 将其移动到您想要的位置:

fs.rename(files.upload.path, 'yournewfilename', function (err) { throw err; });
于 2011-06-15T23:24:00.887 回答
4

表单是否设置为 enctype="multipart/form-data"?

我只使用过 Express - Express 示例运行良好:

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

于 2011-04-04T20:17:37.463 回答