我想使用Multer在我的NodeJs应用程序中由vuejs中的前端定义的特定目录中上传一个文件。
这是我第一次申请multer
后端代码为:
...
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const storage = multer.diskStorage({
destination: (req, file, cb) => {
//req.body.idUser is undefined here
let destinationPath = path.join("upload_file", req.body.idUser);
if (!fs.existsSync(destinationPath)) {
fs.mkdirSync(destinationPath);
}
cb(null, destinationPath);
},
filename: (req, file, cb) => {
let newFileName = Date.now() + path.extname(file.originalname);
cb(null, newFileName);
},
});
const upload = multer({ storage });
app.post(
"/file/add",
upload.fields([{ name: "newfile" }, { name: "idUser" }]),
(req, res) => {
res.json({
response: "file uploaded",
});
},
);
...
前端代码是:
...
async sendDocument(event){
const file = event.target.files[0]
const form = new FormData()
form.append("newfile", file, file.name)
form.append("idUser", this.getIdUser)
const opts =
{
method: "POST",
body: form,
}
const url = "http://localhost:3000/file/add";
try{
await fetch(url, opts)
.then(function (response) {
return response.json();
})
.then(function (res) {
console.log(res)
});
}catch(err){
console.log(err)
}
},
...
我尝试使用console.log逐步进行调试,以检查storage
中未定义req.body.idUser
的原因,我需要它来完成destinationPath
如果用静态值(如"toto"
)替换req.body.idUser
,则一切正常
在前面,this.getIdUser
工作正常,req.body.idUser
在app.post
中工作正常
谢谢你的帮忙
1条答案
按热度按时间c90pui9n1#
请先尝试将ID追加到表单: