Roc*_*cky 3 vue.js axios vuejs2
我正在尝试发送带有图像的表单。注意:我不想将图像保存在数据库中,我想将它保存在我在服务器上创建的文件夹中,然后将图像的链接添加到数据库中。
从服务器端我知道如何处理这个,但我不知道如何从字体端做到这一点。换句话说,如何使用 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>
Run Code Online (Sandbox Code Playgroud)
现在我的问题是如何使用 axios 上传图像以及输入名称。此外,我想使用相同的方法即var product发送。
A standard (mostly) approach will be to split the logic in two, if you want to save the image path on your product, you firstly need to upload the photo to the server and return their path.
pseudo example:
component's data
{
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)
})
}
Run Code Online (Sandbox Code Playgroud)
在这个问题中没有任何特定于 Vue 的内容。使用 axios 发送 POST 请求,最简单的方法是获取 html 表单的 formData 并将其作为 data 参数传递给 Axios。要在 Vue 中执行此操作,只需为您的表单标签提供一个 ref,然后从该表单创建一个 formData。
<form ref="myForm">
// then in your method...
var myFormData = new FormData(this.$refs.myForm)
axios({
method: 'post',
url: 'myurl',
data: myFormData,
config: { headers: {'Content-Type': 'multipart/form-data' }}
})
Run Code Online (Sandbox Code Playgroud)