nodejs文件上传
Nodejs file upload
我收到这个错误:
var oldpath = files.filetoupload.path;
类型错误:无法读取未定义的 属性 'path'
在此代码中:
var http = require('http');
var formidable = require('formidable');
var fs = require('fs');
http.createServer(function (req, res) {
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.path;
var newpath = 'C:/Users/Your Name/' + files.filetoupload.name;
fs.rename(oldpath, newpath, function (err) {
if (err) throw err;
res.write('File uploaded and moved!');
res.end();
});
});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="fil`enter code here`etoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
}).listen(8080);
使用 w3c 学校网站:https://www.w3schools.com/nodejs/nodejs_uploadfiles.asp
检查你的输入类型文件。
你需要给它起一个名字:filetoupload
<input type="file" name="filetoupload">
我收到这个错误: var oldpath = files.filetoupload.path; 类型错误:无法读取未定义的 属性 'path'
在此代码中:
var http = require('http');
var formidable = require('formidable');
var fs = require('fs');
http.createServer(function (req, res) {
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.path;
var newpath = 'C:/Users/Your Name/' + files.filetoupload.name;
fs.rename(oldpath, newpath, function (err) {
if (err) throw err;
res.write('File uploaded and moved!');
res.end();
});
});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="fil`enter code here`etoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
}).listen(8080);
使用 w3c 学校网站:https://www.w3schools.com/nodejs/nodejs_uploadfiles.asp
检查你的输入类型文件。 你需要给它起一个名字:filetoupload
<input type="file" name="filetoupload">