vue上传图片的示例代码
时间: 2023-07-26 13:42:17 浏览: 50
好的,以下是一个基于Vue.js的图片上传示例代码:
```html
<template>
<div>
<input type="file" ref="fileInput" @change="onFileChange" />
<button @click="uploadImage">上传图片</button>
<img v-if="imageUrl" :src="imageUrl" alt="uploaded image" />
</div>
</template>
<script>
export default {
data() {
return {
imageFile: null,
imageUrl: null,
};
},
methods: {
onFileChange(e) {
this.imageFile = e.target.files[0];
this.imageUrl = URL.createObjectURL(this.imageFile);
},
async uploadImage() {
const formData = new FormData();
formData.append('image', this.imageFile);
try {
const response = await axios.post('/api/upload-image', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
console.log('Image uploaded:', response.data);
} catch (error) {
console.error(error);
}
},
},
};
</script>
```
这个示例代码包括一个文件上传框、一个上传按钮和一个预览上传图片的img标签。当用户选择图片后,会将图片对象保存在`imageFile`中,并使用`URL.createObjectURL`方法将图片对象转换成URL,赋值给`imageUrl`,以便在img标签中显示预览图片。当用户点击上传按钮时,我们创建一个`FormData`对象,将图片对象附加到其中,然后使用axios库发送POST请求到服务器的`/api/upload-image`端点,并在请求头中设置`Content-Type`为`multipart/form-data`。请注意,这里使用了async/await语法来处理异步请求。