vue+elementUI使用文件上传功能

192 阅读1分钟

示例如下

template

<el-form-item label="选择文件">
    <el-upload
      class="upload-demo"
      ref="upload"
      :limit="1"
      :file-list="fileList"
      :on-change="handleChange"
      :action="uploadUrl"
      :show-file-list="true"
      :on-success="onSuccess"
      :on-error="onError"
      :auto-upload="false"
    >
      <el-button type="primary" slot="trigger">选取文件</el-button>

      <el-button
        type="primary"
        @click="handleSubmit"
        style="margin-left: 10px;"
        >上传文件</el-button
      >
    </el-upload>
</el-form-item>

js

<script>
export default {
 data() {
      return {
            // 上传文件
            fileList: [],
            uploadUrl: "",
            uploadfileForm: {
                fileList: null,
            },
      }
 },
 methods:{
      // 上传文件
      onSuccess(res) {
        console.log(res); // 这里是调用网络接口返回的内容,根据接口返回的内容进行判断
        if (+res.code === 0) {
          this.queryFileUpload.data.fileUrl = res.data;
        } else {
          this.$message.error("上传失败");
        }
      },
      onError(res) {
        console.log(res);
        this.$message.error("创建失败");
      },
      handleChange(file, fileList) {
        if (fileList.length > 0) {
          this.uploadfileForm.fileList = [fileList[fileList.length - 1]];
        }
      },
      handleSubmit() {
        // 上传接口
        this.uploadUrl = `${rootUrl}commApp/file`; // 这里,读者换成实际项目中的上传接口
        this.$nextTick(() => {
          this.$refs.upload.submit();
        });
      },
   }

}
</script>