const app = getApp(); // pages/story/a.ts Component({ /** * 组件的属性列表 */ properties: { chooseAvatar: { type: Boolean, value: false, }, }, /** * 组件的初始数据 */ data: {}, /** * 组件的方法列表 */ methods: { GetExtensionFileName(pathfilename) { const reg = /(\\+)/g; const pString = pathfilename.replace(reg, "#"); //用正则表达式来将\或\\替换成# const arr = pString.split("#"); // 以“#”为分隔符,将字符分解为数组 例如 D Program Files bg.png const lastString = arr[arr.length - 1]; //取最后一个字符 const arr2 = lastString.split("."); // 再以"."作为分隔符 return arr2[arr2.length - 1]; //将后缀名返回出来 }, handleAfterRead(e) { this.uploadFile(e.detail.file).then((res) => { this.triggerEvent("file", res as object); }); }, handleChooseAvatar(e) { this.uploadFile({ fileType: "image", tempFilePath: e.detail.avatarUrl, size: 0, }).then((res) => { this.triggerEvent("file", res as object); }); }, uploadFile(item) { wx.showLoading({ title: "正在上传", }); return new Promise((resolve, reject) => { let url = `${app.globalData.upFileUrl}?r=file-service/upload-`; if (item.fileType === "image") { url += "img"; } else if (item.fileType === "video") { url += "video"; } else if (item.fileType === "audio") { url += "audio"; } else { url += "doc"; } wx.uploadFile({ filePath: item.tempFilePath, name: "file", url, success: (res) => { wx.hideLoading(); const data = JSON.parse(res.data); const expandJson = { fileId: "", name: data.data.Url, size: (item.size / 1024).toFixed(2), fileUrl: data.data.Url, suffix: this.GetExtensionFileName(data.data.Url), type: item.fileType, imgUrl: "", }; if (item.fileType === "image") { expandJson.imgUrl = data.data.Url; } if (item.fileType === "video") { expandJson.imgUrl = data.data.SnapshotUrl; } resolve(expandJson); }, fail() { wx.hideLoading(); reject(new Error("上传失败")); }, }); }); }, }, }); export {};