javascript 使用 NodeJS 和 node-formidable 上传文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5530610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:31:30  来源:igfitidea点击:

Upload file using NodeJS and node-formidable

javascriptfile-uploadnode.jsserverside-javascript

提问by KingDave

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."

我使用 node.js 和强大的模块成功上传文件,保存在磁盘上的文件格式错误(编码错误)例如,如果我上传图像,我无法查看它,如果我上传txt 文件 gedit 提供以下信息:“gedit 无法检测字符编码。请检查您是否尝试打开二进制文件。从菜单中选择字符编码,然后重试。”

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

回答by BCG

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.

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

Look at:

看着:

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

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() 将其移动到您想要的位置,而不是尝试再次将文件写入磁盘:

fs.rename(files.upload.path, 'yournewfilename', function (err) { throw err; });

回答by johans

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

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

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

我只在 Express 中使用了强大的 - Express 示例工作正常:

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

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