关于vue在for循环中使用XMLHttpRequest请求图片流
参见https://www.cnblogs.com/shaokevin/p/9796882.html
关于vue在for循环中使用XMLHttpRequest请求图片流
<!--
编写记录:
类说明:上传按钮组件
创建: 2019年-4月–06日 李跃跃
修改:
-->
<template>
<div>
<div @click="clickUploadMethod" style="margin-top:-10px;margin-bottom: 10px;">
<el-upload :disabled="querydisabled" :action="actionUrl" :file-list="fileList" list-type="picture-card" :auto-upload="true" ref="upload" :data="uploadData" :on-preview="handlePictureCardPreview" :on-success="handleSuccessMethod" :on-progress="handleProgressMethod" :before-remove="beforeRemoveMethod" :on-remove="removeMethod" :before-upload="uploadCheckMethod" :headers="headers" :class="{hide:hideUploadEdit}">
<i slot="default" class="el-icon-plus"></i>
</el-upload>
</div>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
</div>
</template>
<script>
import CookieUtil from '@/common/util/CookieUtil'
var perNum = sessionStorage.getItem('perNum');
export default {
props: ['paramData', 'fileTypeArr', 'getImageUrl'],
data() {
return {
//Url
actionUrl: '', //上传的地址
getByArticleNumUrl: this.baseJson.baseUrl + this.baseJson.articlemicroService + '/articleDirectory/findByArticleNum', //根据物品编号查物品信息
uploadData: {}, //上传时附带的额外参数uploadParam:{},
headers: {},
uploadFileSize: 5,
accordWith: true, //文件类型是否符合,默认符合
dialogVisible: false, //预览弹出框
dialogImageUrl: '', //预览图片地址
fileList: [],
hideUploadEdit: false, //是否显示添加框
querydisabled: false, //查看禁用
};
},
mounted() {
this.headers = {
'Authorization': "Bearer " + CookieUtil.mutations.getCookie("accessToken")
};
if(this.paramData.type == 'update') {
this.querydisabled = false;
this.getByarticleNumMethod(this.paramData.row.articleNum);
}
if(this.paramData.type == 'query') {
this.querydisabled = true;
this.hideUploadEdit = true;
this.getByarticleNumMethod(this.paramData.row.articleNum);
}
},
methods: {
async getImgMethod(val) {
let that = this;
var xmlHttp;
for(var i = 0; i < val.length; i++) {
xmlHttp = that.creatXMLHttpRequest();
var mapVal = {
uid: val[i].fileNum,
};
var vals = await that.sendHttpMethod(xmlHttp, that.getImageUrl, val[i].uuidName, i);
that.$set(mapVal, "url", vals);
that.fileList.push(mapVal);
if(that.paramData.type == 'query') {
that.hideUploadEdit = true;
} else {
that.hideUploadEdit = that.fileList.length >= 3;
}
}
},
creatXMLHttpRequest() {
var xmlHttp;
if(window.ActiveXObject) {
return xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if(window.XMLHttpRequest) {
return xmlHttp = new XMLHttpRequest();
}
},
sendHttpMethod(xmlHttp, url, param, index) {
let that = this;
return new Promise((resolved, rejected) => {
xmlHttp.timeout = 0;
xmlHttp.withCredentials = false;
xmlHttp.open("GET", url + '/' + param, true);
xmlHttp.setRequestHeader('content-type', 'application/json');
xmlHttp.setRequestHeader("Authorization", "Bearer " + CookieUtil.mutations.getCookie("accessToken"));
xmlHttp.responseType = 'blob';
//可以将`xhr.responseType`设置为`"blob"`也可以设置为`" arrayBuffer"`
//xhr.responseType = 'arrayBuffer';
xmlHttp.onload = function() {
if(this.status === 200) {
resolved(window.URL.createObjectURL(xmlHttp.response));
} else {
rejected();
}
}
xmlHttp.send(null);
});
},
//根据物品编号查询物品
getByarticleNumMethod(articleNum) {
this.$http.get(this.getByArticleNumUrl + '/' + articleNum, {
_timeout: 3000
}).then((response) => {
this.$nextTick(() => {
if(response.data.fileNums.length > 0) {
this.getImgMethod(response.data.fileNums);
}
});
})
.catch(function(response) {
this.$message({
showClose: true,
message: '网络连接失败!',
type: 'error'
});
})
},
//预览
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
},
//点击上传
clickUploadMethod() {
//更新资料文件
if(this.paramData.type == 'update') {
this.uploadData = {
uploadParam: JSON.stringify(this.paramData.row),
};
this.actionUrl = this.paramData.uploadFileUrl;
} else {
//新增文件
this.uploadData = {
uploadParam: JSON.stringify(this.paramData.row),
};
this.actionUrl = this.paramData.uploadFileUrl;
}
},
// 上传前验证
uploadCheckMethod(file) {
this.accordWith = true;
var maxSize = (this.uploadFileSize) * 1024 * 1024;
var filename = file.name;
var fileNameArr = file.name.split(".");
var uploadFileType = fileNameArr[fileNameArr.length - 1];
if(file.size > maxSize) {
this.accordWith = false;
this.$message.error('文件大小不能超过 ' + this.uploadFileSize + 'MB!');
return false;
}
if(this.fileTypeArr.indexOf(uploadFileType) === -1) {
this.accordWith = false;
this.$message.error('文件类型不符合!');
return false;
}
if(filename.indexOf('$') >= 0 || filename.indexOf(',') >= 0 || filename.indexOf('%') >= 0 ||
filename.indexOf('/') >= 0) {
this.accordWith = false;
this.$message.error('文件名称包含非法字符!');
return false;
}
return true;
},
//上传成功
handleSuccessMethod(response, file, fileList) {
if(response == "exception") {
this.$message({
showClose: true,
type: 'error',
message: '后端错误!'
});
this.hideUploadEdit = fileList.length >= 3;
} else {
var res = {
type: 'add',
url: response
}
this.fileList = fileList;
this.$emit('lisData', res);
this.hideUploadEdit = fileList.length >= 3;
}
},
beforeRemoveMethod(file, fileList) {
if(this.accordWith) {
return this.$confirm('此操作将永久删除该图片, 确认删除?');
}
},
removeMethod(file, fileList) {
if(this.accordWith) {
this.hideUploadEdit = fileList.length > 3;
if(this.paramData.type == 'add') {
var res = {
type: 'delete',
url: file.name,
};
this.$emit('lisData', res);
} else if(this.paramData.type == 'update') {
if(file.name != undefined) { //新上传图片
var res = {
type: 'delete',
url: file.name,
};
} else { //已保存到数据库的图片
var res = {
type: 'delete',
uid: file.uid,
};
}
this.$emit('lisData', res);
}
}
},
//上传中
handleProgressMethod(event, file, fileList) {
this.hideUploadEdit = fileList.length >= 3;
},
}
}
</script>
<style>
.hide .el-upload--picture-card {
display: none;
}
</style>