在使用axios進行上傳文件的坑

在進行文件上傳後臺報錯

在使用axios進行文件上傳時,後臺的grails程序經常或出現不能獲取file的情況 No signature of method

No signature of method: org.springframework.security.web.servletapi.HttpServlet3RequestFactory$Servlet3SecurityContextHolderAwareRequestWrapper.getFile() is applicable for argument types: (java.lang.String) values: [inputFile]
Possible solutions: getXML(), getPart(java.lang.String), getAt(java.lang.String), getAt(java.lang.String), getLocale(), getJSON(). Stacktrace follows: 
java.lang.reflect.InvocationTargetException: null

經過排查不是後臺程序的問題,在前端上傳的時候,需要對數據進行處理
如下處理就能正常獲取上傳的文件了

 html:
 選擇文件: <input type="file" name="fileUpload" id="fileUp" @change="change($event)" ref="inputFile" >

 vuejs:
     change:function(event){
        this.file = event.target.files[0]
      },
      upFile:function(event){
        var data = new FormData();//重點在這裏 如果使用 var data = {}; data.inputfile=... 這樣的方式不能正常上傳
        data.append("inputFile",this.file)
        data.append("title","thisAGoodTitle")
        console.log(data)
        // var cfg = {
        //   'Content-type':'multipart/form-data'
        // }
         let headers = {headers: {"Content-Type": "multipart/form-data"}}
            this.$http.post("http://localhost:8081/api/peixun/vedio/uploadVideo",data,headers).then(function(data){
            console.log(data);
          },function(err){
            console.log("err------: ");
            console.log(err);
          })
      }
後端:
def file = request.getFile('inputFile')
file.transferTo(new File(path,newName))//寫到磁盤

這樣就能將前端的文件上傳到服務器端了
如果不使用這種header,直接將文件按照如下上傳 也是可以正常完成上傳的

 // let headers = {headers: {"Content-Type": "multipart/form-data"}}
this.$http.post("http://localhost:8081/api/peixun/vedio/uploadVideo",data).then(function(data){...})

到此,axios進行文件上傳的問題解決了
標記此文,以後遇到這個問題不用到處找了

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