axios上傳視頻或音頻時後端接口405

最近在做一個後臺管理項目,視頻上傳到騰訊雲點播,音頻上傳到對象存儲。這就需要區分是視頻或音頻了。

當上傳音頻時調用後端給的接口,上傳到對象存儲。

這裏遇到的問題主要是自己對axios不太熟練,導致後臺接口返回405,

HTTP Status 405 – Method Not Allowed


Type Status Report

Message Request method 'GET' not supported

Description The method received in the request-line is known by the origin server but not supported by the target resource.


Apache Tomcat/8.0.0

如下圖所示:

前端代碼如下:

<form ref="vExample" method="post" enctype="multipart/form-data">
        <button
          ref="video_btn"
          type="button"
          :class="(uploaderPercent>0  && uploaderPercent<100) ? 'video_btn_gray' : 'video_btn'"
          @click="vExampleAdd"
          :disabled="(uploaderPercent>0  && uploaderPercent<100)"
        >開始上傳</button>
        <input
          type="file"
          name="upfile"
          style="display:none;"
          accept="audio/mpeg, audio/mp3, video/mp4"
          ref="vExampleFile"
          @change="vExampleUpload"
        >
</form>

vuejs代碼如下:

vExampleAdd: function () {
      this.$refs.vExampleFile.click()
    },
    /**
     * vExample示例。上傳視頻過程。
     **/
    vExampleUpload: function () {
      let self = this
      // 獲取上傳實例
      let videoFile = this.$refs.vExampleFile.files[0]
      let index = ''
      for (let key in UE.instants) {
        index = key
      }
      if (videoFile.type.indexOf("audio") !== -1) {

        axios.post(`${CFG.API_URL}xsnArticle/uploadUeditorVideo`).then(req => {
          console.log("req:", req.data)
          
        }).catch(err => {
          console.error('Error: ', err)
        })


      } else {
        //這裏是視頻上傳到騰訊雲點播的代碼, 這裏沒問題,這篇文章的重點不在這裏
        let uploader = this.tcVod.upload({
          videoFile: videoFile
        })

        self.uploaderInfo = {
          videoInfo: uploader.videoInfo,
          isVideoUploadSuccess: false,
          progress: 0,
          cancel: function () {
            uploader.cancel()
          }
        }

        uploader.on('video_progress', function (info) {
          self.uploaderPercent = parseInt(info.percent * 100 + '%')
        })
        uploader.on('video_upload', function (info) {
          self.uploaderInfo.isVideoUploadSuccess = true
        })
        uploader.done().then(function (doneResult) {
          UE.instants[index].execCommand(
            'insertHtml',
            '<img width="300" height="200" id="video_' +
            doneResult.fileId +
            '" _url="' +
            doneResult.video.url +
            '" alt="' +
            doneResult.fileId +
            '" class="edui-upload-video  vjs-default-skin" src="/static/UEditor/themes/default/images/spacer.gif" style ="background:url(/static/UEditor/themes/default/images/videologo.gif) no-repeat center center; border:1px solid gray;" x5-video-player-type="h5" playsinline webkit-playsinline />'
          )
        }).then(function (videoUrl) {
          self.$refs.vExample.reset()

          self.dialogVisible = false
        })
      }

    },

主要是不太瞭解axios的工作原理,導致調用後端接口時直接就是:

axios.post(`${CFG.API_URL}xsnArticle/uploadUeditorVideo`).then(req => {
          console.log("req:", req.data)
          
        }).catch(err => {
          console.error('Error: ', err)
        })

並沒有給後端傳參數,也並沒有把需上傳的文件傳給後端接口。所以才導致後端接口返回405。

後來經過google,找到一篇文章完美的解決了我的困惑,修改代碼如下:(視頻上傳的代碼這裏省略)

let videoFile = this.$refs.vExampleFile.files[0]
      let index = ''
      for (let key in UE.instants) {
        index = key
      }
      if (videoFile.type.indexOf("audio") !== -1) {

        //在這裏聲明所需上傳的文件參數,並把videoFile賦值給audioData
        const audioData = new FormData();
        audioData.append('upfile', videoFile);

        axios.post(`${CFG.API_URL}xsnArticle/uploadUeditorVideo`, audioData).then(req => {
          console.log("req:", req.data)
          
          
        }).then(function () {
          self.$refs.vExample.reset()

          self.dialogVisible = false
        }).catch(err => {
          console.error('Error: ', err)
        })


      }

打印出數據了接口爲200.後臺也可以獲取到上傳的音頻,並把鏈接發送給了前端,到此問題得以解決。

總結:當使用axios上傳文件時,需把上傳的文件當成參數傳給後端,表單需這樣設置

const audioData = new FormData();

audioData.append('upfile', videoFile);

也有的人說需要設置

'Content-Type': 'multipart/form-data' 

其實並沒有必要。

 

有用的鏈接:

https://github.com/axios/axios/issues/318

https://www.jianshu.com/p/85247afabdea

https://blog.csdn.net/u012049760/article/details/71159800

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章