obs.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import ObsClient from "esdk-obs-browserjs/src/obs"
  2. export const uploadToOBS = async (file, progressCallback, type, cancelCallback) => {
  3. try {
  4. const obsClient = new ObsClient({
  5. access_key_id: process.env.VUE_APP_OBS_ACCESS_KEY_ID,
  6. secret_access_key: process.env.VUE_APP_OBS_SECRET_ACCESS_KEY,
  7. server: process.env.VUE_APP_OBS_SERVER,
  8. timeout: 1200,
  9. })
  10. const fileName = file.name || ""
  11. const upload_file_name = new Date().getTime() + "." + fileName.split(".")[fileName.split(".").length - 1]
  12. const date = new Date()
  13. const year = date.getFullYear()
  14. const month = date.getMonth() + 1
  15. const strDate = date.getDate()
  16. const uploadDay = `${year}${month}${strDate}`
  17. const videoKey = `userVideo/${uploadDay}/${upload_file_name}`
  18. const courseKey = `course/${uploadDay}/${upload_file_name}`
  19. const key = type === 1 ? courseKey : videoKey
  20. var callback = (transferredAmount, totalAmount, totalSeconds) => {
  21. const progress = Number.parseInt((transferredAmount * 100.0) / totalAmount)
  22. if (progressCallback) {
  23. progressCallback(progress)
  24. }
  25. }
  26. return new Promise((resolve, reject) => {
  27. let isCancelled = false
  28. if (cancelCallback) {
  29. cancelCallback({
  30. cancel: () => {
  31. console.log("Cancelling OBS upload")
  32. isCancelled = true
  33. reject(new Error("Upload cancelled by user"))
  34. },
  35. })
  36. }
  37. obsClient.putObject(
  38. {
  39. Bucket: process.env.VUE_APP_OBS_BUCKET,
  40. Key: key,
  41. Body: file,
  42. ProgressCallback: callback,
  43. },
  44. (err, result) => {
  45. if (isCancelled) {
  46. return // Don't process result if cancelled
  47. }
  48. if (err) {
  49. reject(err)
  50. console.error("Error-->" + err)
  51. } else {
  52. const a = {
  53. ...result,
  54. urlPath: key,
  55. }
  56. console.log("上传成功", a)
  57. resolve(a)
  58. }
  59. },
  60. )
  61. })
  62. } catch (error) {
  63. console.error("Error during upload:", error)
  64. throw error
  65. }
  66. }