gpt4 book ai didi

javascript - 无法在 Nodejs 中执行 FileUpload 程序

转载 作者:行者123 更新时间:2023-12-03 08:43:01 24 4
gpt4 key购买 nike

我无法使用 NodeJS 上传文件并出现以下异常。

异常(exception):

TypeError: Cannot read property 'file' of undefined
at c:\nital\my-data\my-sample-apps\nodejs\tutorialspoint-samples\Sample37.js:22:26
at Layer.handle [as handle_request] (c:\nital\my-data\my-sample-apps\nodejs\tutorialspoint-samples\node_modules\express\lib\router\layer.js:95:5)
at next (c:\nital\my-data\my-sample-apps\nodejs\tutorialspoint-samples\node_modules\express\lib\router\route.js:131:13)
at Immediate.<anonymous> (c:\nital\my-data\my-sample-apps\nodejs\tutorialspoint-samples\node_modules\multer\lib\make-middleware.js:52:37)
at Immediate.immediate._onImmediate (timers.js:431:18)
at processImmediate [as _immediateCallback] (timers.js:374:17)

我用 google 搜索了一下,发现 req.files API 在 Express 4 框架中不再可用,http://expressjs.com/api.html#req 中提到了这一点。

因为我对 NodeJS 很陌生,所以不知道如何解决这个问题。有人可以指导吗?下面列出了我的实际程序。

FileUploadDemo.js

//Express framework demo. File Upload demo
var express = require('express');
var app = express();
var fs = require("fs");

var bodyParser = require('body-parser');
var multer = require('multer');

app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: false}));
var upload = multer({dest: 'C:/tmp/'});

app.get('/upload.html', function (req, res) {
res.sendFile(__dirname + "/" + "upload.html");
});

//uploading the file here
//app.post('/file_upload', function (req, res) {
app.post('/file_upload', upload.single('file'), function (req, res) {
console.log(req.files.file.name);
console.log(req.files.file.path);
console.log(req.files.file.type);

var file = __dirname + "/" + req.files.file.name;
fs.readFile(req.files.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if (err) {
console.log(err);
} else {
response = {
message: 'File uploaded successfully',
filename: req.files.file.name
};
}
console.log(response);
res.end(JSON.stringify(response));
});
});
});

var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port)
});

最佳答案

由于您使用了 upload.single(),因此可以通过 req.file 而不是 req.files.file 访问该文件。如果您上传了多个文件(upload.array() 或其他文件),则可以使用 req.files 访问它。

关于javascript - 无法在 Nodejs 中执行 FileUpload 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33000043/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com