我是node.js的新手,可以从各种训练营,网站等来源学习它。 我想在node.js和express.js框架中使用强大的模块上传文件。每次我运行此代码时,都会显示错误。...
var oldpath = file.fileupload.path;
^
TypeError: Cannot read property 'path' of undefined
我已经使用主体解析器来接收文件名。
Node.js代码:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var formidable = require("formidable");
var fs = require("fs");
var PORT = process.env.PORT || 5000
app.set("view engine","ejs");
app.use(bodyParser.urlencoded({extended: true}));
app.get("/" , function(req, res){
res.render("form");
});
app.post("/fileupload" , function(req, res){
var fileupload = req.body.filetoupload;
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files){
var oldpath = files.fileupload.path;
var newpath = "C:/Users/ayush/"+files.fileupload.name;
fs.rename(oldpath, newpath, function(err){
if(err)
console.log(err);
else{
res.write("File Uploaded");
res.end();
}
});
});
});
app.listen(PORT, function(){
console.log("Server started");
});
<!DOCTYPE html>
<html>
<head>
<title>FileUpload</title>
</head>
<body>
<form action="/fileupload" method="POST">
<label>
File:
<input type="file" name="filetoupload" enctype="multipart/form-data">
</label>
<button>Submit</button>
</form>
</body>
</html>
答案 0 :(得分:2)
我也是新手,但是form.ejs中的表单enctype应该在<form>
标记中。
代替:
<form action="/fileupload" method="POST">
尝试:
<form action="/fileupload" method="POST" enctype="multipart/form-data">
您现在应该拥有文件对象。
干杯
标记
答案 1 :(得分:0)
这是一个完整的工作示例:
upload.js
'use strict';
const fss = require('fs')
const pth = require('path');
const exp = require('express');
const swg = require('swig');
const efm = require("formidable");
const app = exp();
const thm = swg.compileFile(pth.join(__dirname, '', 'upload.html'));
app.listen(9009);
app.get(`/`, async (q, r) => r.send(thm({ msg: "Select a File to Upload" })));
app.get(`/:msg`, async (q, r) => r.send(thm({ msg: q.params.msg })));
app.post('/upload', (r, q) => {
var form = new efm.IncomingForm();
form.parse(r, (e, p, f) => {
let dir = pth.join(__dirname, '', '/media/');
if (!fss.existsSync(dir)) {
fss.mkdirSync(dir);
}
let nPth = dir + f.file.name;
try {
fss.accessSync(nPth, fss.F_OK);
q.redirect("/File Exists");
} catch (file_e) {
let err = fss.renameSync(f.file.path, nPth);
q.redirect(err ? "/Error" : "/File Uploaded");
}
});
});
fss.access
进行“A-SYNC”操作。upload.html
<h3>{{msg}}</h3>
<br/>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>