Create new post
这是 POST 请求。
router.post("/add-story", upload.single('photo'), async(req, res) => {
try{
let post = new Post();
post.title = req.body.title;
post.description = req.body.description;
post.photo = req.file.location;
post.body = req.body.body;
post.snippet = req.body.snippet;
await post.save();
res.json({
status: true,
message: "Successfully saved."
});
} catch(err) {
res.status(500).json({
success: false,
message: err.message
});
}
});让我们监视文件 中的 change 事件。这样可以确保每次用户的上传行为触发 updatePhoto 方法并把文件数据储存到 this.photo。
编码去收集所有的数据并发送请求
// vue组件的其他部分
data () {
return {
title: '',
body: '',
description: '',
snippet: '',
photo: {} // 储存文件数据
};
},
methods: {
updatePhoto (files) {
if (!files.length) return;
// 存储文件数据
this.photo = {
name: files[0].name,
data: files[0]
};
},
createPost() {
let formData = new FormData();
formData.append('title', this.title);
formData.append('body', this.body);
formData.append('description', this.description);
formData.append('snippet', this.snippet);
formData.append('photo', this.photo.data, this.photo.name);
PostService.createPost(formdata)
.then(() => {
console.log('success');
});
}
}
// vue组件的其他部分