使用NodeJS和节点强大的上传文件 [英] Upload file using NodeJS and node-formidable
问题描述
保存在磁盘上的文件是某种不好的格式(坏编码)
例如如果我上传图片,我无法查看它,如果我上传一个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!');
});
});
问题是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;});
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!');
});
});
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; });
这篇关于使用NodeJS和节点强大的上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!