我一直在尝试向mongoDB添加一个带有图像的产品。Postman测试是成功的,但是当我尝试从前端进行测试时,我得到了这个错误:无法读取正确的路径。我知道我错过了一些东西,因为我不能在我的html文件输入中使用v-model。你能帮帮忙吗?
前端
<template>
<div class="add-rope">
<div class="add-rope-inner">
<form @submit.prevent="handleSubmitForm" enctype = "multipart/form-data">
<h1>Add</h1>
<input type="file" class="add-rope-input" placeholder="image" name="image">
<input type="text" class="add-rope-input" placeholder="Naslov" v-model="ropes.title">
<input type="text" class="add-rope-input" placeholder="Promjer" v-model="ropes.diameter">
<input type="number" class="add-rope-input" placeholder="cijena" v-model="ropes.price">
<input type="number" class="add-rope-input" placeholder="mjerna jedinica" v-model="ropes.cartQuantity">
<input type="text" class="add-rope-input" placeholder="kolicina u skladistu" v-model="ropes.totalQuantity">
<textarea class="add-rope-textarea" placeholder="Opis" v-model="ropes.description"></textarea>
<button class="add-rope-button">Dodaj</button>
</form>
</div>
</div>
</template>
<script>
import axios from "axios";
import router from "@/router";
export default {
data() {
return {
ropes: {
title: '',
description: '',
image:'',
diameter: '',
price: '',
cartQuantity:'',
totalQuantity: ''
}
}
},
methods: {
async handleSubmitForm() {
try {
await axios.post('http://localhost:3000/api/ropes', this.ropes)
.then(() => {
this.$router.push('/crud')
this.ropes = {
title: '',
description: '',
image:'',
diameter: '',
price: '',
cartQuantity:'',
totalQuantity: ''
}
router.go(-1)
})
} catch (error) {
console.log(error)
}
}
}
}
</script>这是后端部分:
router.post('/', upload.single('image'), async (req, res) => {
//create a new user
console.log(req.file)
const rope = new Rope({
title: req.body.title,
description: req.body.description,
image: req.file.path,
diameter: req.body.diameter,
price: req.body.price,
cartQuantity: req.body.cartQuantity,
totalQuantity: req.body.totalQuantity
});
try {
await rope.save();
res.status(201).json(rope);
console.log(req.body)
} catch (err) {
res.status(400).send(err);
}
});发布于 2021-09-06 10:49:19
您可以使用form data上传图片,如下所示:
html:
<input @change="setPhoto" type="file" name="photo" id="photo"/>方法:
setPhoto(e) {
this.photo = e.target.files[0] || e.dataTransfer.files[0];
this.url = URL.createObjectURL(this.photo);
}创建表单数据:
let fd = new FormData();
fd.append("photo", this.photo);https://stackoverflow.com/questions/69072163
复制相似问题