通过Element-ui upload实现文件上传(一次请求上传多个不同字段的文件)

1.一次请求上传单个文件

通过submit()方法:

html:

  <el-form-item
          label="单个文件上传">
          <el-upload
            ref="upload"
            class="upload-demo"
            drag
            multiple
            :headers="upload.headers"
            :action="upload.url"
            :data="upload.data"
            :auto-upload="false"
            :disabled="upload.isUploading"
            :on-change="handleFileChange"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处,或<em>点击上传</em>
              <!-- <div>支持一次上传多个 / 支持 mp4 格式视频</div> -->
            </div>
          </el-upload>
   </el-form-item>

代码:

<script>
    export default {
       data() {
    return {
      // 用户导入参数
      upload: {
        isUploading: false, // 是否禁用上传
        url:
          process.env.VUE_APP_BASE_API + 上传接口 , // 请求地址
        headers: { Authorization: "Bearer " + 获取的token值 }, // 设置上传的请求头部
        data: {}, // 上传的额外数据,用于文件名
      },
    };
  },
    method:{
 /** 处理上传的文件发生变化 */
    handleFileChange(file, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1);
      }
    },
    /** 处理文件上传中 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true; // 禁止修改
    },
    /** 文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      // 提示成功,并刷新
      this.$modal.msgSuccess("上传成功");
    },
}
};
</script>

3.实现上传:

this.$refs.upload.submit();

2.一次请求上传多个不同字段的文件

首先通过new formData 创建一个对象示例,然后通过append来添加要上传的键和值到表单里面

html:

   <el-form-item label="一次接口上传不同字段的文件">
          <el-upload
            class="upload-demo"
            drag
            multiple
            :action="url"
            :auto-upload="false"
            :on-change="handleFileChange"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处,或<em>点击上传</em>
              <!-- <div>支持一次上传多个 / 支持 mp4 格式视频</div> -->
            </div>
          </el-upload>
        </el-form-item>
    <el-form-item label="一次接口上传不同字段的文件">
          <el-upload
            class="upload-demo"
            drag
            multiple
            :action="url"
            :auto-upload="false"
            :on-change="handleFileChange2"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处,或<em>点击上传</em>
            </div>
          </el-upload>
        </el-form-item>

代码:


data(){
 return{
        url: process.env.VUE_APP_BASE_API, // 请求地址(process设置环境变量)
        form : {
        name: undefined,
        comment: undefined,
        coverFile: undefined,
        essentialsImgFile: undefined,
      };
   }
}

method:{
 /** 处理上传的文件发生变化 */
    handleFileChange(file, fileList) {
      this.form.coverFile = file.raw;
      if (fileList.length > 1) {
        fileList.splice(0, 1);
      }
    },
    /** 处理上传的文件发生变化 */
    handleFileChange2(file, fileList) {
      this.form.essentialsImgFile = file.raw;
      if (fileList.length > 1) {
        fileList.splice(0, 1);
      }
    },
    // 文件上传按钮
    submitForm(){
         let formData = new FormData();
         // 可以使用FormData.append来添加键/值对到表单里面;
         // 传数值
         // formData.append('name', id);
         // 传文件 
         // formData.append('files', file);
         for (const key in this.form) {
           if (this.form[key]) {
            formData.append(key, this.form[key]);
          }
        }
        // createExperiment 封装上传文件的接口
        createExperiment(formData).then((res) => {
          this.$modal.msgSuccess("新增成功");
        });
   }
}

append()方法会自动识别你上传的是文件还是数值。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 首先安装axios和element-ui: ``` npm install axios element-ui --save ``` 2. 在需要使用el-upload组件的页面中,引入axios和element-ui: ```javascript import axios from 'axios' import { Upload, MessageBox } from 'element-ui' ``` 3. 在template中使用el-upload组件: ```html <el-upload class="upload-demo" action="/api/upload" :on-change="handleUpload" :before-upload="beforeUpload" :headers="headers" :data="uploadData" :auto-upload="false" :file-list="fileList" :on-remove="handleRemove" :on-success="handleSuccess" :on-error="handleError" > <el-button slot="trigger" size="small" type="primary">选取文件</el-button> <el-button style="margin-left: 10px;" size="small" type="success" @click="upload">上文件</el-button> <div slot="tip" class="el-upload__tip">只能上jpg/png文件,且不超过500kb</div> </el-upload> ``` 其中,action属性指定了上文件的api地址;before-upload属性指定了上文件前的校验函数;headers属性和data属性分别指定了请求的header和请求的参数;auto-upload属性设置为false,表示不自动上文件;file-list属性绑定了已上文件列表;on-remove、on-success和on-error分别指定了文件移除、上成功和上失败的回调函数。 4. 在methods中添加上文件的相关函数: ```javascript methods: { beforeUpload(file) { const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'; const isLt500k = file.size / 1024 < 500; if (!isJPG) { this.$message.error('上头像图片只能是 JPG/PNG 格式!'); } if (!isLt500k) { this.$message.error('上头像图片大小不能超过 500KB!'); } return isJPG && isLt500k; }, handleUpload() { // 当上文件列表发生变化时调用 }, upload() { this.$refs.upload.submit(); }, handleRemove(file, fileList) { // 当文件列表中的某个文件被移除时调用 }, handleSuccess(res, file, fileList) { // 当文件成功时调用 }, handleError(err, file, fileList) { // 当文件失败时调用 } } ``` 5. 在handleSuccess函数中发起axios请求: ```javascript handleSuccess(res, file, fileList) { if (res.code === 0) { this.$message.success('上成功'); // 上成功后,将文件信息添加到fileList中 const { id, name, url } = res.data; fileList[fileList.length - 1].id = id; fileList[fileList.length - 1].name = name; fileList[fileList.length - 1].url = url; } else { this.$message.error('上失败'); } }, ``` 在这个函数中,我们判断了上结果的code,如果为0则表示上成功,将文件信息添加到fileList中;否则表示上失败,弹出提示信息。 6. 在created生命周期函数中设置请求header: ```javascript created() { this.headers = { Authorization: `Bearer ${localStorage.getItem('token')}` }; } ``` 在这里,我们将请求header设置为包含Authorization字段的对象,其值为从localStorage中获取的token。 7. 在methods中定义上文件的函数: ```javascript upload() { this.$refs.upload.submit(); } ``` 该函数调用了el-upload组件的submit方法,用于上文件。 8. 最后,在methods中定义handleUpload函数: ```javascript handleUpload() { // 获取上文件列表 const files = this.$refs.upload.uploadFiles; // 遍历上文件列表,发起axios请求 files.forEach(file => { const formData = new FormData(); formData.append('file', file.raw); axios.post('/api/upload', formData, { headers: { 'Content-Type': 'multipart/form-data', Authorization: `Bearer ${localStorage.getItem('token')}` }, onUploadProgress: (progressEvent) => { // 显示上进度条 const percent = Math.floor((progressEvent.loaded / progressEvent.total) * 100); this.$set(file, 'percentage', percent); } }).then(res => { if (res.code === 0) { this.$message.success('上成功'); // 上成功后,将文件信息添加到fileList中 const { id, name, url } = res.data; this.fileList.push({ id, name, url }); } else { this.$message.error('上失败'); } }).catch(err => { this.$message.error('上失败'); }); }); } ``` 在这个函数中,我们获取上文件列表,遍历上文件列表,发起axios请求,将文件信息添加到fileList中。同时,我们通过设置onUploadProgress回调函数,实时更新上进度条。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值