vue+element-ui上传图片点击按钮上传并带参数给后台formData格式
element
A Vue.js 2.0 UI Toolkit for Web
项目地址:https://gitcode.com/gh_mirrors/eleme/element
免费下载资源
·
之前做的图片上传需求是自动上传并且只带header,这次需要传参数给后台并且格式是formData,非自动上传,而是点击按钮上传,让我琢磨了半天。
需求图片如下
html代码如下
<div class="img-list">
<div class="img" v-for="(item,index) in imgList" :key="index">
<img :src="item" alt="">
<div>
<span></span>
<i @click="deleteImg(item)"></i>
</div>
</div>
<div style="clear:both;"></div>
</div>
<div class="upload-btn">
<div class="upload-left">
<input type="text" v-model="fileName" placeholder="请选择文件">
<el-upload
class="upload-demo"
:action="global"
:headers="headers"
:show-file-list="false"
:auto-upload="false"
ref="upload"
:data="resData"
:on-change="imgBroadcastChange"
:onSuccess="uploadSuccess"
>
<el-button size="small" type="primary" class="file-btn"><i class="file-icon"></i>
</el-button>
</el-upload>
</div>
<div class="upload-rig">
<el-button @click="startUpload()">开始上传</el-button>
</div>
<div style="clear:both;"></div>
</div>
:auto-upload="false" 取消自动上传,:headers="headers",
this.headers = {
"Content-Type": "multipart/form-data"
};设置header
js效果实现如下:
imgBroadcastChange(file, fileList){
// debugger
this.file = file.raw;
this.fileName = file.name;
},
uploadSuccess(res, file) {
},
startUpload(){
this.resData = {
uid: localStorage.getItem("uid"),//用户登录之后服务器返回的用户唯一uid
token: localStorage.getItem("token"),//用户登录之后服务器返回的标识用户的token,这两个值有的没有的可以不加
action:"uploadStationPictureUrl",
station_id:this.imgStationId,
};
const formData = new FormData();
formData.append("uid", this.resData.uid);
formData.append("token", this.resData.token);
formData.append("action", this.resData.action);
formData.append("station_id", this.resData.station_id);
formData.append('file', this.file);
this.$api({
method: "post",
url: "/api.php/DeviceManage/index",
data: formData,
})
.then(su => {
if (su.data.code == 1) {
this.$TyMessage.success("上传成功");
this.imgList.push(su.data.picture_url);
} else if (su.data.code == 300) {
this.$router.push("/login");
this.$TyMessage.error(su.data.message);
} else {
this.$TyMessage.error(su.data.message);
}
})
.catch(err => {});
},
在change函数中把file.raw存储下来,用于点击上传图片的时候传给后台,
const formData = new FormData();
formData.append("uid", this.resData.uid);
formData.append("token", this.resData.token);
formData.append("action", this.resData.action);
formData.append("station_id", this.resData.station_id);
formData.append('file', this.file);
将数据格式转换成formData格式。
GitHub 加速计划 / eleme / element
54.06 K
14.63 K
下载
A Vue.js 2.0 UI Toolkit for Web
最近提交(Master分支:3 个月前 )
c345bb45
7 个月前
a07f3a59
* Update transition.md
* Update table.md
* Update transition.md
* Update table.md
* Update transition.md
* Update table.md
* Update table.md
* Update transition.md
* Update popover.md 7 个月前
更多推荐
已为社区贡献5条内容
所有评论(0)