我正在尝试连同图像一起发送表格。 注意:我不想将图像保存在数据库中,我想将它保存在我在服务器上创建的文件夹中,只需添加图像到数据库的链接。
从服务器端我知道如何处理这个,但我不知道如何从字体端执行此操作。换句话说,如何使用 axios 将图像发送到服务器。
<template>
<input type="text" class="form-control" id="specdesc" v-model="product.specdesc" name="specdesc" placeholder="Enter your name">
<input type="file" name="image" id="image" accept="image/*" >
<button type="submit" class="btn btn-sm btn-primary"@click.prevent="Submit()"> Submit</button>
</template>
<script>
export default {
name: 'Addproduct',
data(){
return{
image: '',
product:{
specdesc:'',
},
}
},
methods:{
Submit(){
var _this=this
// console.log(this.image)
console.log(this.selectedCategory.category_name)
var product = {
specification:this.product.specdesc,
imagename:this.image
}
this.$http.post('http://localhost:3000/api/companyproducts',product)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log("error.response");
});
}
},
}
</script>
现在我的问题是如何使用 axios 上传图像以及输入名称。此外,我想使用相同的方法,即 var product
来发送。
最佳答案
一个标准的(大部分)方法是将逻辑一分为二,如果你想在你的产品
上保存图片路径,你首先需要将照片上传到服务器并返回他们的路径。
伪例子:
组件的数据
{
imagePath: '',
productSpect: ''
}
``
``html
<input type="text" v-model="productSpect" />
<input type="file" @change="uploadImage" name="image" id="image" accept="image/*" >
<button type="submit" @click.prevent="submit"> Submit</button>`
``
**uploadImage method**
uploadImage (e) {
let img = e.target.files[0]
let fd= new FormData()
fd.append('image', img)
axios.post('/upload-image', fd)
.then(resp => {
this.imagePath = resp.data.path
})
}
**submit method**
submit () {
let data = {
imagePath: this.imagePath,
productSpect: this.productSpect
}
axios.post('/path/to/save', data)
}
**edited method to handle just only 1 image on the server**
Change the input `@change` to just save the img on a property under data():
<input type="file" @change="image = e.target.file[0]" name="image" id="image" accept="image/*" >
submit() {
let fd= new FormData()
fd.append('image', this.image)
axios.post('/upload-image', fd)
.then(resp => {
this.imagePath = resp.data.path
let data = {
imagePath: this.imagePath,
productSpect: this.productSpect
}
axios.post('/path/to/save', data)
})
}
关于vue.js - 如何使用 axios 将图像上传到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49299643/