Tôi chỉ đang học node.js và gặp khó khăn khi tạo tệp tải lên đơn giản bằng cách sử dụng express và multer.Loại lỗi Node.js: Không thể đọc thuộc tính 'tệp' không xác định
Dưới đây là hình thức:
Upload ImageTrong tôi configure.js
tôi có:
app.use(express.static(path.join(__dirname, 'public')));
app.use(multer({dest:'../public/upload/temp'}).single('file'));
Và image.js
điều khiển:
create: function(req, res) {
var saveImage = function() {
console.log(req.body);
var possible = 'abcdefghijklmnopqrstuvwxyz',
imgUrl = '';
for(var i=0; i < 6; i+=1) {
imgUrl += possible.charAt(Math.floor(Math.random() * possible.length));
}
var tempPath = req.files.file.path, //<line 55 error
ext = path.extname(req.files.file.name).toLowerCase(),
targetPath = path.resolve('./public/upload/' + imgUrl + ext);
if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext === '.gif') {
fs.rename(tempPath, targetPath, function(err) {
if (err) throw err;
res.redirect('/images/' + imgUrl);
});
} else {
fs.unlink(tempPath, function() {
if (err) throw err;
res.json(500, {error: 'Only image files are allowed.'});
});
}
};
saveImage();
},
Tuy nhiên tôi nhận được lỗi này khi tôi cố gắng để tải lên một hình ảnh:
TypeError: Cannot read property 'file' of undefined
at saveImage (/home/pc/node-dev/test-proj/controllers/image.js:55:37)
at module.exports.create (/home/pc/node-dev/test-proj/controllers/image.js:76:9)
at Layer.handle [as handle_request] (/home/pc/node-dev/test-proj/node_modules/express/lib/router/layer.js:95:5)
at next (/home/pc/node-dev/test-proj/node_modules/express/lib/router/route.js:131:13)
at Route.dispatch (/home/pc/node-dev/test-proj/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/pc/node-dev/test-proj/node_modules/express/lib/router/layer.js:95:5)
at /home/pc/node-dev/test-proj/node_modules/express/lib/router/index.js:277:22
at Function.process_params (/home/pc/node-dev/test-proj/node_modules/express/lib/router/index.js:330:12)
at next (/home/pc/node-dev/test-proj/node_modules/express/lib/router/index.js:271:10)
at urlencodedParser (/home/pc/node-dev/test-proj/node_modules/body-parser/lib/types/urlencoded.js:95:37)
Và khi tôi đăng nhập đối tượng req
, file
là không có:
{ title: 'myimage', description: 'something' }
Trên thực tế, đoạn mã chỉ là một phiên bản được sửa đổi một chút mà tôi đã đọc trong số this book, sử dụng tốc độ nhanh 3. Vì vậy, về cơ bản tôi chỉ cập nhật nó với phần multer
.
Tôi tự hỏi có gì sai ở đây và cách khắc phục.
Bạn đã bao giờ tìm thấy một giải pháp khả thi cho điều này với multer? Tôi đã thử sửa chữa được liệt kê dưới đây, và thay đổi nó để req.file và req.path dường như làm việc, nhưng bây giờ ví dụ từ cuốn sách chuyển hướng đến/hình ảnh/tuyến đường mà không thành công đặt tên hoặc nhận tệp. – Dave
Bạn var tempPath = req.file.path; var ext = path.extname (req.file.originalname) .toLowerCase(); var targetPath = path.resolve ('./ public/upload /' + imgUrl + ext); – iansari