13 使用Vue + FormData + axios实现图片上传功能实战
warning:
这篇文章距离上次修改已过188天,其中的内容可能已经有所变动。
<template>
<div>
<input type="file" @change="previewImage" />
<button @click="uploadImage">上传图片</button>
</div>
</template>
<script>
import axios from 'axios';
export default {
methods: {
previewImage(event) {
// 预览图片
this.image = event.target.files[0];
},
uploadImage() {
// 创建FormData对象
const formData = new FormData();
formData.append('image', this.image);
// 发送请求
axios.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(response => {
// 处理响应
console.log(response.data);
})
.catch(error => {
// 处理错误
console.error(error);
});
}
},
data() {
return {
image: null
};
}
};
</script>
这段代码展示了如何在Vue中使用FormData和axios来上传图片。它包括了图片的选择、上传的实现,并处理了可能出现的错误。这是一个简洁且有效的上传图片的解决方案。
评论已关闭