一、问题
- 需求:需要将图片上传至后端并回显展示,或展示所需数据
二、解决
-
利用Element组件
Upload
上传组件进行解决 -
其中HTML部分代码如下所示:
<!-- 上传 --> <el-upload :show-file-list="false" action="" :http-request="uploadImg"> <el-input v-model="img" placeholder="请上传"></el-input> <img src="@/assets/image/task/file.png" alt=""/> </el-upload> <!-- 回显 --> <img :src="img" alt=""/>
-
data()
中的数据如下:data(){ return{ img: '' // 存放回显数据 } }
-
上传的方法
uploadImg
如下:// 上传队伍队徽 async uploadImg(files) { let form = new FormData() form.append('file', files.file) const res = await this.$postFile(`${this.$url}/src/request_url_in_here`, form) this.img = res.url }
-
其中
$postFile
为二次封装axios
请求,封装好后挂载到Vue
实例对象上面,代码如下:export async function $_post_file(url, obj = {}) { /* request payload */ return await axios({ method: "post", url: url, headers: { 'session': "", "Content-Type": "'multipart/form-data'" }, transformRequest: [ function (data) { return data; } ], data: obj }).then(res => { return res.data }) }
-
配置好后点击输入框后即可选择图片文件进行上传,上传成功后会接收到一个图片在服务器上的地址,将这个地址作为参数动态绑定到要回显的
img
元素中的src
上即可回显。