123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- const tencentBucket = "daya-online-1303457149"
- const ossType = "tencent"
- function fileUpload({ host, token }, { fileName, file }) {
-
- fileName = addTimestampBeforeExtension(fileName)
- return new Promise((res, rej) => {
- getUploadSign(fileName, host, token)
- .then(resUploadSign => {
- if (resUploadSign.code === 200) {
- try {
- onOnlyFileUpload(resUploadSign.data.signature, {
- fileName,
- file
- })
- .then(resUpload => {
- if (resUpload.statusCode === 200) {
- res(resUpload.Location.includes("http") ? resUpload.Location : `https://${resUpload.Location}`)
- } else {
- rej("")
- }
- })
- .catch(() => {
- rej("")
- })
- } catch {
- rej("")
- }
- } else {
- rej("")
- }
- })
- .catch(() => {
- rej("")
- })
- })
- }
- const getUploadSign = (fileName, host, token) => {
- const fileUrl = `pptList/${filePath || "errPath/"}` + fileName
- return ajaxRequest(
- `${host}/edu-app/open/getUploadSign?pluginName=${ossType}`,
- "POST",
- {
- "Content-Type": "application/json",
- Authorization: token
- },
- {
- postData: {
- key: fileUrl
- },
- pluginName: ossType,
- bucketName: tencentBucket,
- filename: fileUrl
- }
- )
- }
- const onOnlyFileUpload = (signature, params) => {
- const cos = new COS({
- Domain: "https://oss.dayaedu.com",
- Protocol: "https",
- getAuthorization: async (options, callback) => {
- callback({ Authorization: signature })
- }
- })
- return cos.uploadFile({
- Bucket: tencentBucket ,
- Region: "ap-nanjing" ,
- Key: `pptList/${filePath || "errPath/"}${params.fileName}`,
-
- Body: params.file,
- SliceSize: 1024 * 1024 * 500 ,
- onProgress: function (progressData) {
-
- }
- })
- }
- function ajaxRequest(url, method = "GET", headers = {}, body = null) {
- return new Promise((resolve, reject) => {
- const xhr = new XMLHttpRequest()
- xhr.open(method, url, true)
-
- for (const [key, value] of Object.entries(headers)) {
- xhr.setRequestHeader(key, value)
- }
- xhr.onload = function () {
- if (xhr.status >= 200 && xhr.status < 300) {
- resolve(JSON.parse(xhr.responseText))
- } else {
- reject(new Error(`HTTP error! status: ${xhr.status}`))
- }
- }
- xhr.onerror = function () {
- reject(new Error("Network error occurred"))
- }
- xhr.send(method === "GET" ? null : JSON.stringify(body))
- })
- }
- function addTimestampBeforeExtension(filename) {
- const dotIndex = filename.lastIndexOf(".")
- const name = filename.substring(0, dotIndex)
- const extension = filename.substring(dotIndex)
- return `${name}_${Date.now()}${extension}`
- }
|