<form action="/upload" method="post">
<input type="file" name="avatar" id="avatarinput" onchange="readfichier()">
<button type='submit'>Save</button>
</form>
服務器
app.post('/upload', upload.single('avatar'), function (req, res, next) {
console.log(req.file);
fs.rename(req.file.path, 'uploads/' req.file.originalname, function (err) {
if (err) throw err;
console.log('renamed complete');
});
res.end('Success');
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})
我收到此錯誤:TypeError: Cannot read properties of undefined (reading 'path')
uj5u.com熱心網友回復:
首先,您需要使用磁盤存盤引擎來完全控制將檔案存盤到磁盤。
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
cb(null,file.fieldname '-' Date.now() '.' file.mimetype.split('/').reverse()[0]);
}
})
const upload = multer({ storage: storage })
現在,定義您的路由并將 multer 添加為中間件。
app.post('/upload', upload.single('avatar'), function (req, res, next) {
console.log(req.file);
fs.rename(req.file.path, 'uploads/' req.file.originalname, function (err) {
if (err) throw err;
console.log('renamed complete');
});
res.end('Success');
})
在之前的答案中也很好地描述了這一點。但是您缺少的是添加enctype="multipart/form-data"到您的 HTML 表單中。在這里閱讀更多關于我們為什么需要這樣做的資訊。
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="avatar" id="avatarinput" onchange="readfichier()">
<button type='submit'>Save</button>
</form>
我希望這能解決你所有的問題。如果沒有,請參考這個答案。
uj5u.com熱心網友回復:
我想這是你唯一的代碼。
首先,您必須將 multer 定義為您的 api 的中間件
然后你必須告訴你的 multer 你想在哪里存盤你的影像
我猜它在你的磁盤中
所以你的服務器代碼看起來像這樣
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req,file,cb){
cb(null, './uploads')
},
filename: function (req,file,cb){
cb(null,file.fieldname '-' Date.now() '.' file.mimetype.split('/').reverse()[0]);
},
});
var upload = multer({storage: storage});
app.post('/upload', upload.single('avatar'), function (req, res, next) {
console.log(req.file);
fs.rename(req.file.path, 'uploads/' req.file.originalname, function (err) {
if (err) throw err;
console.log('renamed complete');
});
res.end('Success');
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/468502.html
標籤:javascript 穆尔特
上一篇:如何在洗掉前添加確認訊息?
下一篇:過濾嵌套物件并回傳值以及父鍵
