使用 NodeJS 和 node-formidable 上传文件
我使用node.js和强大的模块成功上传文件, 保存在磁盘上的文件格式错误(编码错误) 例如,如果我上传图像,我无法查看它,如果我上传 txt 文件,gedit 提供以下消息: “gedit 无法检测到字符编码。 请检查您是否没有尝试打开二进制文件。 从菜单中选择字符编码,然后重试。”
以下是代码:
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!');
});
});
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!');
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
表单是否设置为 enctype="multipart/form-data"?
我只使用过 Express 的 formidable - Express 示例工作正常:
https:// github.com/visionmedia/express/tree/master/examples/multipart
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
问题是 files.upload 不是文件的内容,它是来自 node-formidable 的 File 类的实例。
看看:
https://github.com/felixge/node- formidable/blob/master/lib/file.js
您无需再次尝试将文件写入磁盘,只需像这样访问上传文件的路径并使用 fs.rename() 将其移动到您想要的位置:
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: