美文网首页
vue最简单el-upload上传formdata带参数

vue最简单el-upload上传formdata带参数

作者: litielongxx | 来源:发表于2020-10-24 12:59 被阅读0次

    el-upload自动最简单方式formdata,上传方式。

    <template>
    <el-upload
                style="display:inline-block"
                :limit="5"
                action=''
                class="upload-demo"
                :http-request="changeFile"
                :show-file-list="false"
                ref="upload"
               >
                <el-button :size="size" icon="el-icon-upload" type="primary">上传</el-button>
              </el-upload>
    </template>
    // :http-request="changeFile" 阻止默认上传方式
    //action必填选,没用但得填'',否则报错
    
    methods:{
    changeFile (file) {
          console.log('file', file)
          let fd = new FormData()
          fd.append('file', file.file)// 传文件
          fd.append('second_path', '上传路径')
          let self = this
         // this.loading = false
          fetch(this.uploadApi, {//fetces6语法,同axios/ajax作用
            method: 'POST',
            headers: {
              credentials: 'same-origin'
              // 'Content-Type': 'multipart/form-data',不用写这个,写了报错
            },
            body: fd//不为data为body否则报错
          })
            .then(res => res.json())
            .then(res => {
              console.log(res)
            //报错提示
              if (res.code === -100) {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
               // this.loading = true
                return
              }
              self.loadData(0)
            }).catch(function (e) {
             // this.loading = true
              console.log( e)
            })
    }
    

    ps:【参考来源】(https://www.cnblogs.com/smile-fanyin/p/12495012.html
    formdata传参其实时append加入new formData特殊点而已,其余和正常请求一样。
    当上述请求不可以时,可换用下种(前者python接口可用,后者java,具体跟后台有关,不行时,可以试试)

     let fd = new FormData()
          fd.append('file', file.file)// 传文件
          fd.append('second_path', this.query.second_path)
          let self = this
          this.loading = true
    
          reIdService.upload(fd).then().catch()//直接请求把fd当成参数
        //this.$refs.upload.clearFiles();(如果无法二次上传或其他抽风bug)
       //主要是我们没有清除文件造成的,upload为自定义的refs
    

    相关文章

      网友评论

          本文标题:vue最简单el-upload上传formdata带参数

          本文链接:https://www.haomeiwen.com/subject/rnvimktx.html