vue element 手动上传文件

<el-dialog :visible.sync="visible" :title="titles" :close-on-click-modal="false" :close-on-press-escape="false"
    class="videoDialog" width="35%">
    <el-form ref="dataForm" label-width="150px" class="mt15">
<el-upload class="upload-demo" name="file" :http-request="httpRequest" :on-preview="handlePreview"
          :on-remove="handleRemove" :before-remove="beforeRemove" action="1" :file-list="fileList"
          :on-change="handleChange" :auto-upload="false" ref="upload">
          <!-- :before-upload="beforeAvatarUpload" -->
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传doc/docx文件</div>
        </el-upload>
        <div v-if="progressSeen">
          <el-progress :stroke-width="15" :percentage="progress"></el-progress>
        </div>
  </el-form>
    <template slot="footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确认</el-button>
    </template>
  </el-dialog>

export default {
	data(){
		return{
			 progress: 0,
        progressSeen: false,
		}
	},
	methods: {
	//删除
		handleRemove(file, fileList) {
		//接口调用  removeFile(this.dataForm.id).then(response => {})
        removeFile(this.dataForm.id).then(response => {
          if (response.code == 200) {
            this.fileList = fileList
          } else {
            this.$message({
              message: '删除失败!',
              type: 'error'
            });
          }
        })
      },
      //下载
      handlePreview(file) {
        let url=file.url
        //因为文件在本地
        window.open(url)
      },
      //删除之前的询问
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }?`);
      },
      //文件变化时调用
      handleChange(file, fileList) {
        const extension2 = file.name.split(".")[1] === "docx";
        const extension3 = file.name.split(".")[1] === "doc";
        if (!extension2 && !extension3) {
          this.$message({
            message: '上传文件只能是 .docx、.doc 格式!',
            type: 'error'
          });
          this.fileList =[]
          return false
        }else{
          if (fileList.length > 0 & this.fileList.length > 0) {
            this.$confirm('此操作将覆盖当前文件, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.fileList = [fileList[fileList.length - 1]] // 这一步,是 展示最后一次选择的csv文件
            }).catch(() => {
              this.fileList = [fileList[0]]
            });
          } else {
            this.fileList = [fileList[0]]
          }
        }
      },
      httpRequest(param) {
        let that = this
        let fileObj = param.file // 相当于input里取得的files
        let fd = new FormData() // FormData 对象
        fd.append('file', fileObj) // 文件对象
        fd.append('id', this.dataForm.id)
        that.submitEdtor(fd)
      },
      submitEdtor(fd) {
        let that = this
        //显示进度
        that.progressSeen = true;
        that.progress = 0
        this.$refs["dataForm"].validate(valid => {
          if (valid) {
          //进度条
            const interval = setInterval(() => {
              if (that.progress >= 99) {
                clearInterval(interval)
                return
              }
              that.progress += 1
            }, 20)
          //接口调用  uploadFile(fd).then(response => {})
              uploadFile(fd).then(response => {
                if (response.code === 200) {
                  this.process = 100
                  this.progressSeen = false
                  this.$message({
                    message: '上传成功',
                    type: 'success',
                    duration: 500,
                    onClose: () => {
                    }
                  })
                }
              });
          }
        });
      },
      /** 提交按钮 */
      dataFormSubmit: debounce(function() {
        if (this.fileList.length > 0) {
        //手动上传文件
          this.$refs.upload.submit()
        } else {
          this.$message({
            message: '请选择上传的设备模板',
            type: 'error',
            duration: 500,
            onClose: () => {
            }
          })
        }
      })
	}
}
要实现Vue Element文件上传,可以使用ElUpload组件。在模板中添加一个el-upload标签,并设置相关属性,如ref、:file-list、:auto-upload、:on-change、:limit、drag、action和accept。其中,ref用于在代码中获取上传组件的实例,:file-list绑定文件列表,:auto-upload设置为false表示手动触发上传,:on-change绑定一个方法来处理文件改变事件,:limit设置最大可选文件数量,drag表示是否启用拖拽上传,action为后台接口的URL,accept用于指定接受上传的文件类型。 在methods中,可以定义一些方法来处理文件的操作。例如,handleRemove用于移除文件,handlePreview用于预览文件,handleExceed用于处理超出文件数量限制的情况,beforeRemove用于确认是否移除文件。另外,可以定义submit方法来处理文件上传操作。在该方法中,可以创建一个FormData对象,将文件列表中的文件添加到FormData中,然后调用上传文件的API发送请求。在文件状态改变时的钩子函数OnChange中,可以更新文件列表。 示例代码如下: <el-upload class="upload-demo" ref="upload" :file-list="fileEditList" :auto-upload="false" :on-change="uploadEditFile" :limit="1" drag action accept=".kmz"> <i class="el-icon-upload"></i> <div class="el-upload__text">将文件拖到此处,或点击上传</div> <div class="el-upload__tip" slot="tip" style="display: table-cell; color: gray">只能上传.kmz文件</div> </el-upload> methods: { handleRemove(file, fileList) { console.log(file, fileList); }, handlePreview(file) { console.log(file); }, handleExceed(files, fileList) { this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length fileList.length } 个文件`); }, beforeRemove(file, fileList) { return this.$confirm(`确定移除 ${file.name}?`); }, submit() { var newFile = new FormData(); this.fileList.forEach((item, index) => { newFile.append("file", item.raw); }) uploadFilePort(newFile).then( (res) => { console.log("文件上传res", res); if (res.data.code == 200) { this.$message({ message: "添加成功!!", type: "success" }); } }, (err) => { this.$message.error(err); } ); }, OnChange(file, fileList) { console.log("OnChange-fileList", file, fileList); this.fileList = fileList; }, },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值