vue上传文件

<div>
    <input type="file" class="file"  name="file" @change="uploadBefore">
</div>
export default {
methods:{
            //选择文件
      uploadBefore(){
        var formData = new FormData() // 声明一个FormData对象
        this.formData = new window.FormData() // vue 中使用 window.FormData(),否则会报 'FormData isn't definded'
        this.formData.append('file', document.querySelector('input[type=file]').files[0]) // 'userfile' 这个名字要和后台获取文件的名字一样;
        let file = document.querySelector('input[type=file]').files[0]
        console.log(this.fileName)
        let fileName = file.name.substring(file.name.lastIndexOf(".")+1,file.name.length)
        const fileType = fileName == 'xls'||fileName == 'xlsx'||fileName == 'ppt'||fileName == 'pptx'||fileName == 'doc'||fileName == 'docx'||fileName == 'txt'||fileName == 'pdf'||fileName == 'jpg'||fileName == 'gif'||fileName == 'jpeg'||fileName == 'png'||fileName == 'bmp'||fileName == 'mp3'||fileName == 'mp4';
      //   console.log(file)
      //   console.log(fileName)
      //   console.log(fileType)
        if (!fileType) {
          this.$message.error('上传文件格式不正确,请检查');
          this.numberValidateForm.fileName = ""
        }else{
            
       this.numberValidateForm.fileName = file.name
       }
},   
   // 保存,上传文件
      submitForm() {
            this.saveLoading = true
                 this.$http({
                url: this.$store.state.domian+'/bbt-admin/courseware/upload/'+dynamicppt,
                data: this.formData,
                method: 'post',
                headers: { 
                  'Content-Type': 'multipart/form-data',
                }
            }).then((res => {
               if (res.data.statusCode == 0) {
                 
                  this.$message({message:'操作成功!',type: 'success'})
                  this.dialogTableVisible = false
                  this.getFileList(1);
               
               }
              this.saveLoading = false
              console.log(res)
            })
            )
         
        });
      },   
}


}

  

posted @ 2018-12-14 11:48  慕城蓝就  阅读(1304)  评论(0编辑  收藏  举报