UNPKG

vue-cloud-upload

Version:

基于vue+elementui的通用云上传组件,无缝衔接腾讯云,华为云,阿里云等对象存储平台,开箱即用

6 lines (5 loc) 31.6 kB
(function(p,c){typeof exports=="object"&&typeof module!="undefined"?c(exports,require("vue"),require("element-ui")):typeof define=="function"&&define.amd?define(["exports","vue","element-ui"],c):(p=typeof globalThis!="undefined"?globalThis:p||self,c(p.CloudUpload={},p.Vue,p.ElementUI))})(this,(function(p,c,h){"use strict";var ne=Object.defineProperty,re=Object.defineProperties;var le=Object.getOwnPropertyDescriptors;var Z=Object.getOwnPropertySymbols;var oe=Object.prototype.hasOwnProperty,ce=Object.prototype.propertyIsEnumerable;var q=(p,c,h)=>c in p?ne(p,c,{enumerable:!0,configurable:!0,writable:!0,value:h}):p[c]=h,k=(p,c)=>{for(var h in c||(c={}))oe.call(c,h)&&q(p,h,c[h]);if(Z)for(var h of Z(c))ce.call(c,h)&&q(p,h,c[h]);return p},X=(p,c)=>re(p,le(c));var C=(p,c,h)=>q(p,typeof c!="symbol"?c+"":c,h);var d=(p,c,h)=>new Promise((y,B)=>{var P=x=>{try{E(h.next(x))}catch(z){B(z)}},L=x=>{try{E(h.throw(x))}catch(z){B(z)}},E=x=>x.done?y(x.value):Promise.resolve(x.value).then(P,L);E((h=h.apply(p,c)).next())});class y{static getFileExtension(e){return(typeof e=="string"?e:e.name).split(".").pop().toLowerCase()}static getFileSizeMB(e){return parseFloat((e.size/(1024*1024)).toFixed(2))}static getFileSizeAuto(e){const t=e.size;return t<1024?t+" B":t<1048576?(t/1024).toFixed(2)+" KB":t<1073741824?(t/1048576).toFixed(2)+" MB":(t/1073741824).toFixed(2)+" GB"}static checkFileType(e,t){const i=y.getFileExtension(e);return t.includes(i)}static generatePreviewURL(e){return new Promise((t,i)=>{const a=new FileReader;a.onload=r=>t(r.target.result),a.onerror=r=>i(r),a.readAsDataURL(e)})}static downloadFile(e,t){let i="";if(t)i=t;else{const a=decodeURIComponent(e);i=a.substring(a.lastIndexOf("/")+1).split("?")[0]}fetch(e).then(a=>a.blob()).then(a=>{const r=document.createElement("a");r.href=URL.createObjectURL(a),r.download=i,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(r.href)}).catch(a=>console.error("下载失败:",a))}static getFileType(e){let t="";if(e.name&&e.name!="")t=y.getFileExtension(e);else{if(!e.url)return"other";t=y.getFileExtension(e.url)}if(y.getIfImage(e))return"image";let i="";switch(t){case"doc":case"docx":i="word";break;case"pdf":i="pdf";break;case"ppt":case"pptx":i="ppt";break;case"xls":case"xlsx":case"csv":i="excel";break;case"rar":case"zip":case"7z":case"gzip":case"tar":i="rar";break;case"mp4":case"webm":case"ogg":case"mpeg":i="video";break;case"mp3":case"aac":case"wav":case"flac":case"opus":i="audio";break;case"txt":i="txt";break;default:i="other";break}return i}static getIfImage(e){let t="";if(e.name&&e.name!="")t=y.getFileExtension(e);else if(e.key)t=y.getFileExtension(e.key);else if(e.url)t=y.getFileExtension(e.url);else return!1;return["png","jpg","jpeg","bmp","gif","webp","svg"].some(a=>a===t)}static getFileName(e){if(e.name)return e.name;if(e.key&&e.key!="")return e.key.substring(e.key.lastIndexOf("/")+1).split("?")[0];if(e.url&&e.url!=""){const t=decodeURIComponent(e.url);return t.substring(t.lastIndexOf("/")+1).split("?")[0]}else return""}}function B(s,e,t,i,a,r,o,n){var m=typeof s=="function"?s.options:s;return e&&(m.render=e,m.staticRenderFns=t,m._compiled=!0),r&&(m._scopeId="data-v-"+r),{exports:s,options:m}}const P={props:{visible:{type:Boolean},file:{type:Object,required:!0}},data(){return{currentVisible:this.visible,fileType:"",fileName:"",fileRaw:null,pdfUrl:"",fileContent:"",loading:!1,fullscreen:!1}},computed:{formattedText(){return this.fileContent.replace(/\n/g,"<br>")},dialogWidth(){return this.fileType=="audio"?"30%":"75%"}},methods:{handleOpen(){},handleClose(){this.$emit("update:visible",!1)},initTxtContent(){if(!this.fileRaw)return;const s=new FileReader;s.onload=e=>{this.fileContent=e.target.result},s.readAsText(this.fileRaw)},initPdfContent(){this.pdfUrl=URL.createObjectURL(this.fileRaw)}},watch:{visible(s){this.currentVisible=s},file:function(s){return d(this,null,function*(){if(this.loading=!0,this.fileName=y.getFileName(s),this.fileType=y.getFileType(s),s.raw&&s.raw instanceof File)this.fileRaw=s.raw;else if(this.fileType=="txt"||this.fileType=="pdf")try{const t=yield(yield fetch(s.url)).blob();this.fileRaw=t}catch(e){console.error("文件下载失败:",e);return}switch(this.fileType){case"txt":this.initTxtContent();break;case"pdf":this.initPdfContent();break}this.loading=!1})}}};var L=function(){var e=this,t=e._self._c;return t("el-dialog",{attrs:{visible:e.currentVisible,title:e.fileName,"custom-class":"file-preview-dialog","append-to-body":"",fullscreen:e.fullscreen,width:e.dialogWidth},on:{"update:visible":function(i){e.currentVisible=i},open:e.handleOpen,close:e.handleClose},scopedSlots:e._u([{key:"title",fn:function(){return[t("div",{staticClass:"dialog-header"},[t("span",[e._v(e._s(e.fileName))]),t("i",{class:["preview-header-icon",e.fullscreen?"el-icon-copy-document":"el-icon-full-screen"],on:{click:function(i){e.fullscreen=!e.fullscreen}}})])]},proxy:!0}])},[t("div",{directives:[{name:"loading",rawName:"v-loading",value:e.loading,expression:"loading"}],class:["file-preview-content",e.fileType=="audio"?"preview-audio":""]},[e.fileType=="txt"?t("div",{domProps:{innerHTML:e._s(e.formattedText)}}):e._e(),e.fileType=="pdf"?t("iframe",{staticClass:"pdf-container",attrs:{src:e.pdfUrl,frameborder:"0"}}):e._e(),e.fileType=="video"&&e.currentVisible?t("video",{ref:"cloud-upload-video",attrs:{controls:"",src:e.file.url,autoplay:"",preload:"auto",crossorigin:""}}):e._e(),e.fileType=="audio"&&e.currentVisible?t("audio",{attrs:{controls:"",src:e.file.url,autoplay:"",preload:"auto",crossorigin:""}}):e._e()])])},E=[],x=B(P,L,E,!1,null,"ab02c2c8");const z=x.exports,Q="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let V=(s=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(s|=0));for(;s--;)e+=Q[t[s]&63];return e},$=null,T=null,F=null;c.component("el-upload",h.Upload),c.component("el-image",h.Image),c.component("el-tooltip",h.Tooltip),c.component("el-dialog",h.Dialog),c.use(h.Loading.directive);const Y={name:"CloudUpload",inheritAttrs:!1,props:{multiple:{type:Boolean,default:!1},showFileList:{type:Boolean,default:!0},drag:{type:Boolean,default:!1},accept:{type:String},listType:{type:String,default:"picture-card",validator:s=>{const e=["text","picture","picture-card"];return e.includes(s)?!0:(console.error(`listType参数必须是以下值之一: ${e.join(", ")} 当前值: "${s}"将回退到默认值"picture-card"`),!1)}},disabled:{type:Boolean,default:!1},limit:{type:Number},maxSize:{type:Number},size:{type:String,default:"small",validator:s=>{const e=["medium","small","mini"];return e.includes(s)?!0:(console.error(`listType参数必须是以下值之一: ${e.join(", ")} 当前值: "${s}"将回退到默认值"small"`),!1)}},sliceSize:{type:Number,default:1024*1024*10},chunkSize:{type:Number,default:1024*1024*5},fileKey:{type:String,default:"uuid+name",validator:s=>{const e=["uuid","name","uuid+name"];return e.includes(s)?!0:(console.error(`listType参数必须是以下值之一: ${e.join(", ")} 当前值: "${s}"将回退到默认值"uuid+name"`),!1)}},cloudType:{type:String,default:"tencent",validator:s=>{const e=["tencent","huawei","aliyun"];return e.includes(s)?!0:(console.error(`listType参数必须是以下值之一: ${e.join(", ")} 当前值: "${s}"将回退到默认值"tencent"`),!1)}},cloudConfig:{type:Object,required:!0},previewConfig:{type:Object,required:!1},value:{type:Array,default:()=>{}},beforeUpload:{type:Function,required:!1},beforeRemove:{type:Function,required:!1},onExceed:{type:Function,required:!1},onPreview:{type:Function,required:!1},onChange:{type:Function,required:!1}},data(){return{fileList:this.value,previewUrl:"",previewVisible:!1,previewFile:{}}},computed:{getPreviewList(){let s=[];return this.fileList.forEach(e=>{this.getIfImage(e)&&e.url&&s.push(e.url)}),s},getPreviewConfig(){return Object.assign({image:!0,video:!0,audio:!0,word:!1,excel:!1,ppt:!1,txt:!0,pdf:!0,rar:!1},this.previewConfig)}},created(){this.checkAndInit(this.cloudConfig)},beforeDestroy(){$&&$.destroyInstance(),T&&T.destroyInstance(),F&&F.destroyInstance()},methods:{checkAndInit(s){return d(this,null,function*(){const e=["tencent","huawei","aliyun"];switch(this.cloudType?e.includes(this.cloudType)||console.warn(`云平台类型cloudType设置错误,应为${e.join("/")}`):console.warn("未设置云平台类型cloudType!"),this.cloudType){case"tencent":$=(yield Promise.resolve().then(()=>W)).default,$.getInstance(s),yield $.waitForInitialization();break;case"huawei":T=(yield Promise.resolve().then(()=>G)).default,T.getInstance(s),yield T.waitForInitialization();break;case"aliyun":F=(yield Promise.resolve().then(()=>ae)).default,F.getInstance(s),yield F.waitForInitialization();break}})},getImgRef(s){return`previewImg${this.getPreviewList.findIndex(e=>e==s.url)}`},getFileName(s){return y.getFileName(s)},getIfImage(s){return y.getIfImage(s)},getFileType(s){return y.getFileType(s)},getFileIcon(s){const e=this.getFileType(s);return{image:"",video:"icon-video",audio:"icon-audio",rar:"icon-yasuobao",word:"icon-WORD",excel:"icon-EXCEL",ppt:"icon-ppt",txt:"icon-txt",pdf:"icon-Pdf",other:"icon-fujian1"}[e]},getFileLoading(s){var t;if(!s.url)return!0;if(!((t=this.$refs.innerUpload)!=null&&t.uploadFiles))return!1;const e=this.$refs.innerUpload.uploadFiles.find(i=>i.uid==s.uid||i.url==s.url);return e?!!(e.percentage&&e.percentage<1):!1},getFilePercent(s){var t;if(!((t=this.$refs.innerUpload)!=null&&t.uploadFiles))return"";const e=this.$refs.innerUpload.uploadFiles.find(i=>i.uid==s.uid||i.url==s.url);return e?e.percentage&&e.percentage<1?`上传中${Math.round(e.percentage*1e3)/10}%`:e.percentage==1?"上传完成":"加载中":""},customUpload(s){return d(this,null,function*(){const{file:e,onProgress:t,onSuccess:i,onError:a}=s;let r=this.generateKey(e.name);const o=X(k({file:e,key:r,chunkSize:this.chunkSize,sliceSize:this.sliceSize},this.cloudConfig),{onProgress:n=>{console.log("当前进度:",n),t({percent:n}),this.$emit("progress",n,e)}});try{let n;switch(this.cloudType){case"tencent":if(n=yield $.getInstance().uploadFile(o),n.statusCode==200){const m=this.$refs.innerUpload.uploadFiles.findIndex(f=>f.uid==e.uid);let l=this.$refs.innerUpload.uploadFiles[m];const u=Object.assign(l,{url:n.url,key:n.key,result:n});this.$refs.innerUpload.uploadFiles.splice(m,1,u),this.fileList=this.$refs.innerUpload.uploadFiles}break;case"huawei":if(n=yield T.getInstance().uploadFile(o),n.CommonMsg.Status==200){const m=this.$refs.innerUpload.uploadFiles.findIndex(f=>f.uid==e.uid);let l=this.$refs.innerUpload.uploadFiles[m];const u=Object.assign(l,{url:n.url,key:n.key,result:n});this.$refs.innerUpload.uploadFiles.splice(m,1,u),this.fileList=this.$refs.innerUpload.uploadFiles}break;case"aliyun":if(n=yield F.getInstance().uploadFile(o),n.url){const m=this.$refs.innerUpload.uploadFiles.findIndex(f=>f.uid==e.uid);let l=this.$refs.innerUpload.uploadFiles[m];const u=Object.assign(l,{url:n.url,key:n.key,result:n});this.$refs.innerUpload.uploadFiles.splice(m,1,u),this.fileList=this.$refs.innerUpload.uploadFiles}break;default:throw new Error(`Unsupported cloudType: ${this.cloudType}`)}i(n,e),this.$emit("success",n,e),this.$emit("input",this.fileList)}catch(n){a(n,e),this.$emit("error",n,e)}})},generateKey(s){let e="";switch(this.fileKey){case"name":e=`${this.cloudConfig.path}${s}`;break;case"uuid":const t=y.getFileExtension(s);e=`${this.cloudConfig.path}${V()}.${t}`;break;case"uuid+name":e=`${this.cloudConfig.path}${V()}/${s}`;break}return e},onbeforeUpload(s){if(this.beforeUpload&&typeof this.beforeUpload=="function")return this.beforeUpload(s);{let e=!0;if(this.accept){const i=this.accept.split(",").map(a=>a.replace(".",""));e=y.checkFileType(s,i)}const t=this.maxSize?y.getFileSizeMB(s)<this.maxSize:!0;return e?t?!0:(this.$message.error(`文件大小不能超过 ${this.maxSize}MB!`),!1):(this.$message.error(`文件类型必须是 ${this.accept} 中的一种!`),!1)}},handleRemove(s,e){this.fileList=this.fileList.filter(t=>t.uid!=s.uid&&t.url!=s.url),this.$emit("input",this.fileList),this.$emit("remove",s)},handlePreview(s){if(this.onPreview&&typeof this.onPreview=="function")this.onPreview(s);else if(this.getFileType(s)=="image"){const t=this.getImgRef(s);this.$refs[t].clickHandler()}else this.previewFile=s,this.previewVisible=!0},handleDown(s){this.$message.success("文件开始下载,请稍等!");const e=y.getFileName(s);y.downloadFile(s.url,e)},handleExceed(s,e){this.onExceed&&typeof this.onExceed=="function"?this.onExceed(s,e):this.$message.warning(`当前限制最多选择${this.limit}个文件!`)},getFileUrls(){return d(this,null,function*(){for(let s=0;s<this.fileList.length;s++){let e=this.fileList[s];if(!e.url||e.url==""){if(!e.key||e.key==""){console.error("v-model传入文件key为空,无法获取文件地址!");return}switch(this.cloudType){case"tencent":const t=yield $.getInstance().getFileUrlByKey(k({key:e.key},this.cloudConfig));e.url=t,this.fileList.splice(s,1,e);break;case"huawei":if(T){const i=yield T.getInstance().getFileUrlByKey(k({key:e.key},this.cloudConfig));e.url=i,this.fileList.splice(s,1,e)}break;case"aliyun":if(F){const i=yield F.getInstance().getFileUrlByKey(k({key:e.key},this.cloudConfig));e.url=i,this.fileList.splice(s,1,e)}break}}}})}},watch:{cloudType(s){this.checkAndInit(this.cloudConfig)},cloudConfig:{deep:!0,handler(s){this.checkAndInit(s)}},value:{immediate:!0,handler(s){return d(this,null,function*(){this.fileList=s,this.fileList.some(e=>(!e.url||e.url=="")&&e.key&&e.key!="")&&(yield this.checkAndInit(this.cloudConfig),this.getFileUrls())})}}},components:{FilePreview:z}};var H=function(){var e=this,t=e._self._c;return t("div",{class:["cloud-upload","cloud-upload-"+e.size,e.disabled&&e.fileList.length>0?"cloud-upload-disabled":""]},[t("el-upload",e._g(e._b({ref:"innerUpload",attrs:{action:"#","file-list":e.fileList,multiple:e.multiple,accept:e.accept,limit:e.limit,drag:e.drag,"show-file-list":e.showFileList,"on-exceed":e.handleExceed,"on-remove":e.handleRemove,"on-preview":e.handlePreview,"on-change":e.onChange,"before-upload":e.onbeforeUpload,"before-remove":e.beforeRemove,"http-request":e.customUpload,"list-type":e.listType,disabled:e.disabled},scopedSlots:e._u([{key:"file",fn:function({file:i}){return!e.$scopedSlots.file&&e.listType=="picture-card"?[e.getIfImage(i)?t("el-image",{directives:[{name:"loading",rawName:"v-loading",value:e.getFileLoading(i),expression:"getFileLoading(file)"}],ref:e.getImgRef(i),staticClass:"el-upload-list__item-thumbnail",attrs:{"preview-src-list":e.getPreviewList,fit:"contain","element-loading-text":e.getFilePercent(i),src:i.url}}):t("div",{directives:[{name:"loading",rawName:"v-loading",value:e.getFileLoading(i),expression:"getFileLoading(file)"}],staticClass:"el-upload-list__item-thumbnail previewIcon",attrs:{"element-loading-text":e.getFilePercent(i)}},[t("i",{class:["cloud-upload-icon",e.getFileIcon(i)]})]),t("span",{staticClass:"el-upload-list__item-actions"},[e.getPreviewConfig[e.getFileType(i)]&&i.status=="success"?t("span",{staticClass:"el-upload-list__item-preview"},[t("i",{staticClass:"el-icon-view",on:{click:()=>e.handlePreview(i)}})]):e._e(),t("span",{staticClass:"el-upload-list__item-delete"},[t("i",{staticClass:"el-icon-download",on:{click:()=>e.handleDown(i)}})]),e.disabled?e._e():t("span",{staticClass:"el-upload-list__item-delete",on:{click:()=>e.handleRemove(i)}},[t("i",{staticClass:"el-icon-delete"})])]),t("el-tooltip",{staticClass:"item",attrs:{effect:"light",content:e.getFileName(i),placement:"top"}},[t("span",{staticClass:"file-name",on:{click:()=>e.handleDown(i)}},[e._v(e._s(e.getFileName(i)))])])]:void 0}}],null,!0)},"el-upload",e.$attrs,!1),e.$listeners),[e.$scopedSlots.default?e._e():[e.listType=="picture-card"?t("div",{staticClass:"default-content"},[e.disabled?e.fileList.length==0?[t("i",{staticClass:"el-icon-folder-opened",attrs:{slot:"default"},slot:"default"}),t("span",[e._v("暂无文件")])]:e._e():[t("i",{staticClass:"el-icon-upload",attrs:{slot:"default"},slot:"default"}),t("span",[e._v("点击上传")])]],2):t("el-button",{attrs:{size:e.size,type:"primary",disabled:e.disabled}},[e._v("点击上传")])],e._l(e.$scopedSlots,function(i,a){return[e._t(a,null,null,e.scoped)]})],2),t("FilePreview",{attrs:{visible:e.previewVisible,file:e.previewFile},on:{"update:visible":function(i){e.previewVisible=i}}})],1)},ee=[],te=B(Y,H,ee,!1,null,"468d90a3");const D=te.exports;function ie(s){Promise.resolve().then(()=>W).then(e=>{e.default.setExternalCOS(s)})}function se(s){Promise.resolve().then(()=>G).then(e=>{e.default.setExternalOBS(s)})}D.install=function(s){s.component(D.name,D)},typeof window!="undefined"&&window.Vue&&window.Vue.component(D.name,D);const U=class U{constructor(e){C(this,"cosClient",null);C(this,"tempCredential",null);C(this,"secretId",null);C(this,"secretKey",null);C(this,"initPromise",null);e&&e.secretId&&e.secretKey&&(this.secretId=e.secretId,this.secretKey=e.secretKey),this.initPromise=this.initClient(e)}static setExternalCOS(e){this.externalCOS=e}static getInstance(e){return this.instance||e&&(e.secretId&&e.secretKey||e.getTempCredential&&typeof e.getTempCredential=="function")&&(this.instance=new U(e)),this.instance}static waitForInitialization(){return d(this,null,function*(){this.instance&&this.instance.initPromise&&(yield this.instance.initPromise)})}static destroyInstance(){this.instance=null,this.cosClient=null,this.tempCredential=null,localStorage.removeItem("cosCredential");try{const e=localStorage.getItem("cosCacheDatas");if(e){let t=JSON.parse(e);const i=Date.now()-14400*60*1e3;t=t.filter(a=>a.createTime?a.createTime>i:!1),localStorage.setItem("cosCacheDatas",JSON.stringify(t))}}catch(e){console.error("清理过期断点记录失败:",e)}}initClient(e){return d(this,null,function*(){let t=U.externalCOS;if(this.secretId&&this.secretKey)this.cosClient=new t({SecretId:this.secretId,SecretKey:this.secretKey});else{const i=e.getTempCredential;yield this.getTempCredential(i),this.cosClient=new t({getAuthorization:(a,r)=>d(this,null,function*(){try{(!this.tempCredential||this.isCredentialExpired())&&(yield this.getTempCredential(i)),r({TmpSecretId:this.tempCredential.tmpSecretId,TmpSecretKey:this.tempCredential.tmpSecretKey,SecurityToken:this.tempCredential.sessionToken,StartTime:this.tempCredential.startTime,ExpiredTime:this.tempCredential.expiredTime})}catch(o){console.error("获取临时凭证失败:",o)}})})}})}getTempCredential(e){return d(this,null,function*(){let t=localStorage.getItem("cosCredential");if(t&&(t=JSON.parse(t)),t&&!this.isCredentialExpired(t)){this.tempCredential=t;return}try{const i=yield e();i&&typeof i=="object"&&(this.tempCredential={tmpSecretId:i.credentials.tmpSecretId,tmpSecretKey:i.credentials.tmpSecretKey,sessionToken:i.credentials.sessionToken,startTime:i.startTime,expiredTime:i.expiredTime},localStorage.setItem("cosCredential",JSON.stringify(this.tempCredential)))}catch(i){throw new Error("获取临时凭证失败: "+i.message)}})}isCredentialExpired(e=this.tempCredential){return e?Math.floor(Date.now()/1e3)>=e.expiredTime-60:!0}uploadFile({bucket:e,region:t,key:i,file:a,sliceSize:r,chunkSize:o,onProgress:n}){return new Promise((m,l)=>d(this,null,function*(){const u=yield this.isBucketPublicRead({bucket:e,region:t}),f=`${a.name}-${a.size}-${a.lastModified}`;let b="";if(a.size<r)b=i;else{const v=this.getCosDataByKey(f);v?b=v.name:(b=i,this.setCosData(f,i))}this.cosClient.uploadFile({Bucket:e,Region:t,Key:b,Body:a,SliceSize:r,ChunkSize:o,onProgress:v=>{n&&typeof n=="function"&&n(v.percent)}},(v,g)=>{if(v)l(v);else if(this.delCosData(f),u){const S=g.Location.startsWith("https://")?g.Location:"https://"+g.Location;m(k({url:S,key:b,name:a.name},g))}else this.cosClient.getObjectUrl({Bucket:e,Region:t,Key:b,Sign:!0},function(S,w){S?console.log(S):m(k({url:w.Url,key:b,name:a.name},g))})})}))}getFileUrlByKey({bucket:e,region:t,key:i}){return new Promise((a,r)=>d(this,null,function*(){let o=yield this.isBucketPublicRead({bucket:e,region:t});try{let n={Bucket:e,Region:t,Key:i,Sign:!0};o&&(n.Sign=!1);const m=yield this.cosClient.getObjectUrl(n);a(m)}catch(n){r("获取文件地址失败!")}}))}getCosDataByKey(e){let t=[];const i=localStorage.getItem("cosCacheDatas");i&&(t=JSON.parse(i));const a=t.findIndex(r=>r.key==e);return a>=0?t[a]:null}setCosData(e,t){let i=[];const a=localStorage.getItem("cosCacheDatas");a&&(i=JSON.parse(a));const r=i.findIndex(o=>o.key==e);r>=0?i[r].name=t:i.push({key:e,name:t,createTime:Date.now()}),localStorage.setItem("cosCacheDatas",JSON.stringify(i))}delCosData(e){let t=[];const i=localStorage.getItem("cosCacheDatas");i&&(t=JSON.parse(i));const a=t.findIndex(r=>r.key==e);a>=0&&(t.splice(a,1),localStorage.setItem("cosCacheDatas",JSON.stringify(t)))}addWatermark(r){return d(this,arguments,function*({bucket:e,region:t,key:i,watermarkText:a}){const o={Bucket:e,Region:t,Key:i,PicOperations:JSON.stringify({is_pic_info:1,rules:[{fileid:`watermark_${i}`,rule:`watermark/2/text/${encodeURIComponent(a)}/fill/IzAwMDAwMA/fontsize/20/dissolve/50/gravity/southeast/dx/20/dy/20`}]})};return new Promise((n,m)=>{this.cosClient.ciPutObjectFromLocalFile(o,(l,u)=>{l?m(l):n(u)})})})}getBucketAcl(i){return d(this,arguments,function*({bucket:e,region:t}){return new Promise((a,r)=>{this.cosClient.getBucketAcl({Bucket:e,Region:t},(o,n)=>{o?r(o):a(n)})})})}isBucketPublicRead(i){return d(this,arguments,function*({bucket:e,region:t}){try{return(yield this.getBucketAcl({bucket:e,region:t})).Grants.some(r=>r.Grantee.URI==="http://cam.qcloud.com/groups/global/AllUsers"&&r.Permission==="READ")}catch(a){return console.error("检查存储桶权限失败:",a),!0}})}};C(U,"instance",null),C(U,"externalCOS",null);let j=U;const W=Object.freeze(Object.defineProperty({__proto__:null,default:j},Symbol.toStringTag,{value:"Module"})),_=class _{constructor(e){C(this,"obsClient",null);C(this,"tempCredential",null);C(this,"accessKeyId",null);C(this,"secretAccessKey",null);C(this,"server",null);C(this,"initPromise",null);e&&e.server&&(this.server=e.server),e&&e.accessKeyId&&e.secretAccessKey&&(this.accessKeyId=e.accessKeyId,this.secretAccessKey=e.secretAccessKey),this.initPromise=this.initClient(e)}static setExternalOBS(e){this.externalOBS=e}static getInstance(e){return this.instance||e&&(e.accessKeyId&&e.secretAccessKey&&!e.getTempCredential||e.getTempCredential&&typeof e.getTempCredential=="function")&&(this.instance=new _(e)),this.instance}static destroyInstance(){this.instance=null,this.obsClient=null,this.tempCredential=null,localStorage.removeItem("obsCredential");try{const e=localStorage.getItem("obsCpDatas");if(e){let t=JSON.parse(e);const i=Date.now()-14400*60*1e3;t=t.filter(a=>a.createTime?a.createTime>i:!1),localStorage.setItem("obsCpDatas",JSON.stringify(t))}}catch(e){console.error("清理过期断点记录失败:",e)}}static waitForInitialization(){return d(this,null,function*(){this.instance&&this.instance.initPromise&&(yield this.instance.initPromise)})}static ensureInitialized(){return d(this,null,function*(){yield this.waitForInitialization()})}initClient(e){return d(this,null,function*(){let t=_.externalOBS;if(this.accessKeyId&&this.secretAccessKey&&!e.getTempCredential)this.obsClient=new t({access_key_id:this.accessKeyId,secret_access_key:this.secretAccessKey,server:this.server});else if(e.getTempCredential)yield this.getTempCredential(e.getTempCredential),this.obsClient=new t({access_key_id:this.tempCredential.accessKeyId,secret_access_key:this.tempCredential.secretAccessKey,security_token:this.tempCredential.securityToken,server:this.server});else throw new Error("缺少必要的认证信息:需要提供永久密钥或getTempCredential函数");this.obsClient.initLog({level:"warn"})})}getTempCredential(e){return d(this,null,function*(){let t=localStorage.getItem("obsCredential");if(t&&(t=JSON.parse(t)),t&&!this.isCredentialExpired(t)){this.tempCredential=t;return}try{const i=yield e();i&&typeof i=="object"&&(this.tempCredential={accessKeyId:i.credential.access,secretAccessKey:i.credential.secret,securityToken:i.credential.securitytoken,expiredTime:i.credential.expires_at},localStorage.setItem("obsCredential",JSON.stringify(this.tempCredential)))}catch(i){throw new Error("获取临时凭证失败: "+i.message)}})}isCredentialExpired(e=this.tempCredential){if(!e)return!0;const t=Date.now(),i=Date.parse(e.expiredTime);return t>=i-60*1e3}ensureValidCredential(e){return d(this,null,function*(){if(e&&(!this.tempCredential||this.isCredentialExpired())){yield this.getTempCredential(e);let t=_.externalOBS;this.obsClient=new t({access_key_id:this.tempCredential.accessKeyId,secret_access_key:this.tempCredential.secretAccessKey,security_token:this.tempCredential.securityToken,server:this.server})}})}uploadFile(m){return d(this,arguments,function*({bucket:e,key:t,file:i,sliceSize:a,chunkSize:r,onProgress:o,getTempCredential:n}){if(yield this.ensureValidCredential(n),i.size<a)try{const l=yield this.obsClient.putObject({Bucket:e,Key:t,SourceFile:i,ProgressCallback:(u,f,b)=>{o&&typeof o=="function"&&o(u/f)}});if(l.CommonMsg.Status<300){const u=yield this.obsClient.getObject({Bucket:e,Key:t,SaveByType:"file"});let f="";if(u.CommonMsg.Status<300&&u.InterfaceResult)f=u.InterfaceResult.Content.SignedUrl;else throw new Error(`附件url获取失败: ${u.CommonMsg.Code}`);return k({url:f,key:t,name:i.name},l)}else throw new Error(`上传失败: ${l.CommonMsg.Code}`)}catch(l){throw new Error(`华为云OBS上传失败: ${l.message}`)}else try{let l=[];const u=localStorage.getItem("obsCpDatas");u&&(l=JSON.parse(u));const f=`${i.name}-${i.size}-${i.lastModified}`,b=l.findIndex(w=>w.key==f),v=b>=0;let g=v?l[b].cp:null,S;if(g?(g.sourceFile=i,S=yield this.obsClient.uploadFile({UploadCheckpoint:g,ProgressCallback:(w,I,R)=>{o&&typeof o=="function"&&o(w/I)},EventCallback:function(w,I,R){if(w=="uploadPartSucceed"){const N=l.findIndex(O=>O.key==f),J=g.parts.findIndex(O=>O.partNumber==I.partNumber);g.parts[J].isCompleted=!0,l[N].cp=g,localStorage.setItem("obsCpDatas",JSON.stringify(l))}}})):S=yield this.obsClient.uploadFile({Bucket:e,Key:t,SourceFile:i,PartSize:r,ProgressCallback:(w,I,R)=>{o&&typeof o=="function"&&o(w/I)},ResumeCallback:function(w,I){g=I,v?l[b].cp=g:(l.push({key:f,cp:g,createTime:Date.now()}),localStorage.setItem("obsCpDatas",JSON.stringify(l)))},EventCallback:function(w,I,R){if(w=="uploadPartSucceed"){const N=l.findIndex(O=>O.key==f),J=g.parts.findIndex(O=>O.partNumber==I.partNumber);g.parts[J].isCompleted=!0,l[N].cp=g,localStorage.setItem("obsCpDatas",JSON.stringify(l))}}}),S.CommonMsg.Status<300){const w=l.findIndex(N=>N.key==f);l.splice(w,1),localStorage.setItem("obsCpDatas",JSON.stringify(l));const I=yield this.obsClient.getObject({Bucket:e,Key:S.InterfaceResult.Key,SaveByType:"file"});let R="";if(I.CommonMsg.Status<300&&I.InterfaceResult)R=I.InterfaceResult.Content.SignedUrl;else throw new Error(`附件url获取失败: ${I.CommonMsg.Code}`);return k({url:R,key:S.InterfaceResult.Key,name:i.name},S)}else throw new Error(`上传失败: ${S.CommonMsg.Code}`)}catch(l){throw new Error(`华为云OBS上传失败: ${l.message}`)}})}getFileUrlByKey({bucket:e,region:t,key:i}){return new Promise((a,r)=>d(this,null,function*(){try{let o={Bucket:e,Key:i,SaveByType:"file"};const n=yield this.obsClient.getObject(o);if(n.CommonMsg.Status<300&&n.InterfaceResult){const m=n.InterfaceResult.Content.SignedUrl;a(m)}else r(`附件url获取失败: ${n.CommonMsg.Code}`)}catch(o){r("获取文件地址失败!")}}))}addWatermark(r){return d(this,arguments,function*({bucket:e,region:t,key:i,watermarkText:a}){try{return{processedUrl:`https://${e}.obs.${t}.myhuaweicloud.com/${i}?x-image-process=image/watermark,text_${encodeURIComponent(a)},color_FFFFFF,size_20,g_se,x_20,y_20`,originalKey:i}}catch(o){throw new Error(`添加水印失败: ${o.message}`)}})}};C(_,"instance",null),C(_,"externalOBS",null);let A=_;const G=Object.freeze(Object.defineProperty({__proto__:null,default:A},Symbol.toStringTag,{value:"Module"})),K=class K{constructor(e){C(this,"ossClient",null);C(this,"initPromise",null);this.initPromise=this.initClient(e)}static setExternalOSS(e){this.externalOSS=e}static getInstance(e){return this.instance||e&&e.getTempCredential&&typeof e.getTempCredential=="function"&&(this.instance=new K(e)),this.instance}static destroyInstance(){this.instance=null,this.ossClient=null;try{const e=localStorage.getItem("ossCptDatas");if(e){let t=JSON.parse(e);const i=Date.now()-14400*60*1e3;t=t.filter(a=>a.createTime?a.createTime>i:!1),localStorage.setItem("ossCptDatas",JSON.stringify(t))}}catch(e){console.error("清理过期断点记录失败:",e)}}static waitForInitialization(){return d(this,null,function*(){this.instance&&this.instance.initPromise&&(yield this.instance.initPromise)})}static ensureInitialized(){return d(this,null,function*(){yield this.waitForInitialization()})}initClient(e){return d(this,null,function*(){const t=yield e.getTempCredential(),i=["accessKeyId","accessKeySecret","stsToken"];let a=!0;if(i.forEach(o=>{t.hasOwnProperty(o)||(console.error(`getTempCredential函数未返回字段${o}`),a=!1)}),!a){this.instance=null;return}let r=K.externalOSS||window.OSS;this.ossClient=new r({secure:!0,authorizationV4:!0,region:e.region,accessKeyId:t.accessKeyId,accessKeySecret:t.accessKeySecret,stsToken:t.stsToken,bucket:e.bucket,refreshSTSToken:e.getTempCredential,refreshSTSTokenInterval:e.refreshSTSTokenInterval||85e3})})}uploadFile(m){return d(this,arguments,function*({bucket:e,region:t,key:i,file:a,sliceSize:r,chunkSize:o,onProgress:n}){try{if(a.size<r){const l=yield this.ossClient.put(i,a,{progress:u=>{n&&typeof n=="function"&&n(u)}});return k({url:l.url,key:i,name:a.name},l)}else{let l;const u=`${a.name}-${a.size}-${a.lastModified}`,f=this.getCptDataByKey(u);let b=f?f.cpt:null;b?l=yield this.ossClient.multipartUpload(f.name,a,{checkpoint:b,progress:(S,w)=>{this.setCptData(u,i,w),n&&typeof n=="function"&&n(S)},parallel:4,partSize:o}):l=yield this.ossClient.multipartUpload(i,a,{progress:(S,w)=>{this.setCptData(u,i,w),n&&typeof n=="function"&&n(S)},parallel:4,partSize:o}),l.res.status==200&&this.delCptData(u);const v={"content-disposition":`attachment; filename=${encodeURIComponent(a.name)}`},g=`https://${e}.${t}.aliyuncs.com/${l.name}`;return k({url:g,key:l.name,name:a.name},l)}}catch(l){throw new Error(`阿里云OSS上传失败: ${l.message}`)}})}getCptDataByKey(e){let t=[];const i=localStorage.getItem("ossCptDatas");i&&(t=JSON.parse(i));const a=t.findIndex(r=>r.key==e);return a>=0?t[a]:null}setCptData(e,t,i){let a=[];const r=localStorage.getItem("ossCptDatas");r&&(a=JSON.parse(r));const o=a.findIndex(n=>n.key==e);o>=0?a[o].cpt=i:a.push({key:e,name:t,cpt:i,createTime:Date.now()}),localStorage.setItem("ossCptDatas",JSON.stringify(a))}delCptData(e){let t=[];const i=localStorage.getItem("ossCptDatas");i&&(t=JSON.parse(i));const a=t.findIndex(r=>r.key==e);a>=0&&(t.splice(a,1),localStorage.setItem("ossCptDatas",JSON.stringify(t)))}addWatermark(r){return d(this,arguments,function*({bucket:e,region:t,key:i,watermarkText:a}){try{return{processedUrl:this.ossClient.signatureUrl(i,{expires:3600,process:`image/watermark,text_${encodeURIComponent(a)},fill_ I0ZGRkZGRg,size_20,g_se,x_20,y_20`}),originalKey:i}}catch(o){throw new Error(`添加水印失败: ${o.message}`)}})}};C(K,"instance",null),C(K,"externalOSS",null);let M=K;const ae=Object.freeze(Object.defineProperty({__proto__:null,default:M},Symbol.toStringTag,{value:"Module"}));p.default=D,p.setExternalCOS=ie,p.setExternalOBS=se,Object.defineProperties(p,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));