我目前正在开发人们可以上传mp3文件和其他内容的功能,作为社交媒体相关应用程序的帖子。我将VueJs用于前端,将nodeJs用于后端。
我在后端找不到任何问题,因为当我尝试通过邮递员上传包含所有必填字段的帖子时,一切正常,并且帖子已上传到数据库等。在我的前端,我尝试可以使用表单数据打包所有内容,在我看来,只有req.body中的文本值(如标题,评论等)才能到达后端,但我不知道文件在哪里。
我正在使用multer,我的代码现在捕获名称为“ audio”的所有文件,并将其存储在服务器上的本地文件夹中。保存到数据库中的内容发生在postPost控制器中。
//in my backend
router.post('/create', multer({storage: fileStorage, fileFilter: fileFilter}).single('audio'), PostController.postPost)
这就是我在VueJS上的CreatePost组件上拥有的
<template>
<div class="form-control">
{{message}}
<!-- <div v-if="withError" class="error" v-html="error"/> -->
<h1 class="form-title">post what you're working on</h1>
<div class="form-control__inputs">
<input type="text" name="title" v-model="title" placeholder="add a title to your post">
<input type="file" id="file" ref="file" v-on:change="handleFileUpload()">
<!-- <input type="text" name="caption" v-model="caption" placeholder="..and a caption"> -->
<textarea name="caption" v-model="caption" placeholder="..and a caption" rows="5" cols="45"></textarea>
</div>
<div class="form-control__actions">
<button @click="createPost" type="submit">post</button>
</div>
</div>
</template>
在脚本部分,我有一个方法,可以使用axios将发布请求发送到后端。
createPost(){
//initialze form data
const formData = new FormData();
formData.set('title', this.title);
formData.set('caption', this.caption);
formData.append('audio', this.file);
try{
// const response = await PostService.createPost({
// formData
// });
axios.post('http://localhost:3000/posts/create', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}
);
}catch(error){
this.message = 'somethinf went wrong'
console.log(error.response.data.error);
// this.error = error.response.data.error;
}
}
当它到达后端路由时,req.file是未定义的。
如果有人可以帮助我解决这一拖延性问题,我将不胜感激!