12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- import ObsClient from "esdk-obs-browserjs/src/obs"
- export const uploadToOBS = async (file, progressCallback, type, cancelCallback) => {
- try {
- const obsClient = new ObsClient({
- access_key_id: process.env.VUE_APP_OBS_ACCESS_KEY_ID,
- secret_access_key: process.env.VUE_APP_OBS_SECRET_ACCESS_KEY,
- server: process.env.VUE_APP_OBS_SERVER,
- timeout: 1200,
- })
- const fileName = file.name || ""
- const upload_file_name = new Date().getTime() + "." + fileName.split(".")[fileName.split(".").length - 1]
- const date = new Date()
- const year = date.getFullYear()
- const month = date.getMonth() + 1
- const strDate = date.getDate()
- const uploadDay = `${year}${month}${strDate}`
- const videoKey = `userVideo/${uploadDay}/${upload_file_name}`
- const courseKey = `course/${uploadDay}/${upload_file_name}`
- const key = type === 1 ? courseKey : videoKey
- var callback = (transferredAmount, totalAmount, totalSeconds) => {
- const progress = Number.parseInt((transferredAmount * 100.0) / totalAmount)
- if (progressCallback) {
- progressCallback(progress)
- }
- }
- return new Promise((resolve, reject) => {
- let isCancelled = false
- if (cancelCallback) {
- cancelCallback({
- cancel: () => {
- console.log("Cancelling OBS upload")
- isCancelled = true
- reject(new Error("Upload cancelled by user"))
- },
- })
- }
- obsClient.putObject(
- {
- Bucket: process.env.VUE_APP_OBS_BUCKET,
- Key: key,
- Body: file,
- ProgressCallback: callback,
- },
- (err, result) => {
- if (isCancelled) {
- return // Don't process result if cancelled
- }
- if (err) {
- reject(err)
- console.error("Error-->" + err)
- } else {
- const a = {
- ...result,
- urlPath: key,
- }
- console.log("上传成功", a)
- resolve(a)
- }
- },
- )
- })
- } catch (error) {
- console.error("Error during upload:", error)
- throw error
- }
- }
|