在使用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进行文件上传的问题解决了
标记此文,以后遇到这个问题不用到处找了

猜你喜欢

转载自blog.csdn.net/shsongtao/article/details/80707467