动漫php网站模板,电子商务做网站,局域网站建设,自己做盗版小说网站一、背景
开发中需要对加密文件进行解码#xff0c;如图片等静态资源。
根据后端给到的url地址#xff0c;返回的是图片文件#xff0c;但是乱码的#xff0c;需要解码成png图片进行展示
二、请求接口
将后端返回的文件转为文件流#xff0c;创建Blob对象来存储二进制…一、背景
开发中需要对加密文件进行解码如图片等静态资源。
根据后端给到的url地址返回的是图片文件但是乱码的需要解码成png图片进行展示
二、请求接口
将后端返回的文件转为文件流创建Blob对象来存储二进制数据通过URL.createObjectURL()方法创建二进制数据的URL将URL赋值给imgData以显示图片。 //初始化图片数据并进行处理initImg() {this.isLoading true//请求携带的参数let param {printType: this.printType,orderIdList: Array.isArray(this.orderIdList) ? this.orderIdList : this.orderIdList.split(,),billTypeList: this.billType.split(,)}let promise//发请求此处是封装的请求promise this.$http.any(post, ${this.$url.payList.getPrintReceipt}, {}, param, null, blob)// 发起POST请求获取打印收据的二进制数据并将结果赋值给promise变量promise.then((res) {let reader new FileReader() // 创建FileReader对象用于读取二进制let response nullreader.onload () {// 如果读取的结果是以{开头则将其解析为JSON对象if (reader.result[0] {) {response JSON.parse(reader.result)this.$message.error(response.msg)} else {this.inChooseCharge falselet fileType png // 设置文件类型为pnglet blob new Blob([res], { type: application/${fileType} }) // 创建Blob对象用于存储二进制数据let data window[window.webkitURL ? webkitURL : URL][createObjectURL](blob) // 通过URL.createObjectURL()方法创建二进制数据的URLthis.imgData data // 将URL赋值给imgData用于显示图片console.log(printinitImg -- imageData, this.imgData)let img new Image()// 当图片加载完成时执行回调函数img.onload () {//对图片宽高比进行判断if (img.width / img.height 1100 / 595) {this.fitWidth true} else {this.fitWidth false}this.$nextTick(() {this.popupDoLayout()})}img.src this.imgData}this.isLoading false}reader.readAsText(res, utf-8) // 以文本格式读取二进制数据}).catch((error) {this.isLoading falseconsole.log(请求失败:, error)})} 说明发请求时要说明是转换成blob 再创建Blob对象存储二进制数据。最主要的还是要多打日志看每一步的结果再做对应操作 MDN文件参考URL.createObjectURL() - Web API 接口参考 | MDN 三、结构
使用img展示图片利用element的image-viewer来进行图片缩放需要从element中引入
div classmain print-box :class{ fit-width: fitWidth, fit-height: !fitWidth } v-elseimg classimg :srcimgData alt预览图 loadpopupDoLayout clickimgData ? getShowViewer(imgData) : null /div classflex bottom-boxel-button typeprimary clickprint :disabled!imgData打印/el-button/div/divel-image-viewer v-ifshowViewer :on-closecloseViewer :url-listviewerImgList / 从element中引入image-viewer使用