vue+el-upload上传多文件,上传中删除,更换和删除

html:

 <el-form-item label="" style="width: 960px;">
          <span slot="label"><span style="color:red;">*</span>音频内容</span>
          <el-upload :action="uploadAudioUrl"
                     :headers="uploadHeaders"
                     :show-file-list="false"
                     accept=".mp3"
                     :on-progress="handleUploadContentAudioProcess"
                     :on-success="handleUploadContentAudioSuccess"
                     multiple
                     ref="audioListUpload1"
                     style="width: 100px;display: inline-block;">

            <el-button size="small" type="primary" @click="isClick='add'">添加音频</el-button>
            <div class="el-form-item__error" style="position: relative" v-if="showErr">请上传音频内容</div>
          </el-upload>

          <el-button type="primary" size="small" @click="sortByList()" style="display: inline-block;position: absolute">
            排 序
          </el-button>
          <div style="margin-top: 10px;">
            <el-table :data="contentList" border stripe size="mini">
              <el-table-column label="序号" type="index" align="center" width="100">
                <template slot-scope="scope">
                  <el-select :value="scope.$index+1" size="mini"
                             @change="((newSequence)=>{changeContentImageSequence(scope.$index+1, newSequence)})">
                    <el-option v-for="index in contentList.length"
                               :key="index"
                               :label="index"
                               :value="index">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column show-overflow-tooltip label="音频名称" prop="name">
                <template slot-scope="scope">
                  <div>
                    <el-popover placement="right"
                                trigger="hover"
                                v-if="scope.row.path != null && scope.row.path !== ''">
                      <audio class="video" height="400"
                             :src="contentBaseUrl + scope.row.path"
                             controls="controls">您的浏览器不支持 audio 标签。
                      </audio>
                      <el-button type="text" slot="reference">{{ scope.row.name}}</el-button>
                    </el-popover>

                    <div v-else>{{ scope.row.name }}</div>
                  </div>
                </template>
              </el-table-column>

              <el-table-column show-overflow-tooltip label="标题" width="400" prop="episodeTitle">
                <template slot-scope="scope">
                  <div v-if="scope.row.status === 'success'">
                    <el-input v-model="scope.row.episodeTitle" placeholder="请输入音频标题内容"></el-input>
                  </div>
                  <el-progress :percentage="getPercentage(scope.row.percentage)"
                               v-if="scope.row.status === 'uploading'">
                  </el-progress>
                </template>
              </el-table-column>

              <el-table-column show-overflow-tooltip label="操作" align="center" width="200">
                <template slot-scope="scope">
                  <el-button type="danger" size="mini" @click="deleteAudio(scope.$index)">删除</el-button>
                  <el-upload style="display: inline-block"
                             :action="uploadAudioUrl"
                             :headers="uploadHeaders"
                             :show-file-list="false"
                             accept=".mp3"
                             :on-progress="handleChangeContentAudioProcess(scope.$index)"
                             :on-success="handleChangeContentAudioSuccess(scope.$index)"
                             multiple
                             ref="audioListUpload">
                    <el-button size="mini" type="primary"  @click="isClick='update'">更换</el-button>
                  </el-upload>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>

js:

//音频上传
      handleUploadContentAudioProcess(event, file, fileList) {
        if (file.status === 'fail') {
          for (let i = 0; i < this.contentList.length; i++) {
            if (this.contentList[i].uid === file.uid) {
              this.contentList.splice(i, 1);
              break;
            }
          }
          return;
        }
        let exist = false;
        for (let i = 0; i < this.contentList.length; i++) {
          if (this.contentList[i].uid === file.uid) {
            this.contentList[i] = file;
            exist = true;
            break;
          }
        }

        if (!exist) {
          this.contentList.push(file);
        }
      },
      handleUploadContentAudioSuccess(response, file) {
        if (response.code === this.$constant.RESPONSE_CODE_LIST.SUCCESS) {
          this.isEpisodeTitleInput = true;

          file.path = response.data[0].path;
          file.audioName = response.data[0].audioName;
          file.totalSeconds = response.data[0].totalSeconds;
          let exist = false;

          for (let i = 0; i < this.contentList.length; i++) {
            if (this.contentList[i].uid === file.uid) {
              this.contentList[i] = file;
              this.$set(this.contentList[i], 'episodeTitle', file.audioName.split(".")[0]);
              exist = true;
              break;
            }
          }

          if (!exist) {
            this.contentList.push(file);
          }

        } else if (response.code === this.$constant.RESPONSE_CODE_LIST.TOKEN_INVALID) {
          this.$message({
            message: response.message,
            type: "error",
            duration: 5 * 1000
          });

          let callback = location.href;

          let baseUrl = process.env.UNION_BASE_URL;
          let reg = new RegExp("\/$");
          if (reg.test(process.env.UNION_BASE_URL)) {
            baseUrl = process.env.UNION_BASE_URL.substring(0, process.env.UNION_BASE_URL.length - 1);
          }

          location.href = baseUrl + "/login?systemId=" + response.data.systemId
              + "&callback=" + encodeURIComponent(callback);
        } else {
          this.$message({
            message: response.message,
            type: "error",
            duration: 5 * 1000
          });

        }
      },
      //更换已上传的
      handleChangeContentAudioProcess(index) {
        return (function (event, file, fileList) {
          if (file.status === 'fail') {
            this.contentList.splice(index, 1);

            return;
          }

          this.isEpisodeTitleInput = false;

          this.contentList.splice(index, 1, file);
        }).bind(this);
      },
      handleChangeContentAudioSuccess(index) {
        return (function (response, file, fileList) {
          if (response.code === this.$constant.RESPONSE_CODE_LIST.SUCCESS) {
            this.isEpisodeTitleInput = true;

            file.path = response.data[0].path;
            file.audioName = response.data[0].audioName;
            file.totalSeconds = response.data[0].totalSeconds;

            this.contentList.splice(index, 1, file);

            this.$set(this.contentList[index], 'episodeTitle', file.audioName.split(".")[0]);

          } else if (response.code === this.$constant.RESPONSE_CODE_LIST.TOKEN_INVALID) {
            this.$message({
              message: response.message,
              type: "error",
              duration: 5 * 1000
            });

            let callback = location.href;

            let baseUrl = process.env.UNION_BASE_URL;
            let reg = new RegExp("\/$"); // eslint-disable-line
            if (reg.test(process.env.UNION_BASE_URL)) {
              baseUrl = process.env.UNION_BASE_URL.substring(0, process.env.UNION_BASE_URL.length - 1);
            }

            location.href = baseUrl + "/login?systemId=" + response.data.systemId
                + "&callback=" + encodeURIComponent(callback);
          } else {
            this.$message({
              message: response.message,
              type: "error",
              duration: 5 * 1000
            });
          }
        }).bind(this);
      },
       //上传进度
      getPercentage(percentage) {
        return Number(percentage.toFixed(0));
      },
      //删除操作
      deleteAudio(index) {
        this.$confirm("确认删除音频文件吗?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        }).then(() => {
        //判断当前文件状态是否 在上传中,
          if (this.contentList[index].status == 'uploading') {
          //是新增上传,或是更换上传处理判断,
            if (this.isClick == 'add') {
              this.$refs.audioListUpload1.abort(this.contentList[index]);
            } else if (this.isClick == 'update') {
              this.$refs.audioListUpload.abort(this.contentList[index]);
            }

          }
          this.contentList.splice(index, 1);
        }).catch(() => {
          return;
        });
      },
       //自然排序排序
      sortByList() {
        if (this.contentList.length <= 1) {
          return
        }
        let episodeTitleList = [];
        for (let j = 0; j < this.contentList.length; j++) {
          episodeTitleList[j] = this.contentList[j].episodeTitle;
        }
        this.$http.post("/api/common/upload/batch/order", {}, {
          strings: episodeTitleList,
          type: 0
        }).then(response => {
          let list = response.data;
          let newlist = [];
          for (let i = 0; i < list.length; i++) {
            for (let j = 0; j < this.contentList.length; j++) {
              if (list[i] == this.contentList[j].episodeTitle) {
                newlist[i] = this.contentList[j];
              }
            }
          }
          this.contentList = newlist;
        });
      },
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
要实现Vue + Axios + El-upload进行文件上传并跨域,需要按照以下步骤进行操作: 1. 在Vue项目安装axios和element-ui。在命令行输入以下命令即可安装: ``` npm install axios element-ui --save ``` 2. 在Vue项目创建一个上传文件的组件,例如FileUpload.vue。在该组件导入axios和element-ui,并且引入El-upload组件。示例代码如下: ```vue <template> <div> <el-upload class="upload-demo" :action="uploadUrl" :on-success="handleUploadSuccess" :before-upload="beforeUpload" :headers="headers" :data="formData" :file-list="fileList"> <el-button size="small" type="primary">点击上传</el-button> </el-upload> </div> </template> <script> import axios from 'axios' import { Message } from 'element-ui' export default { name: 'FileUpload', data () { return { fileList: [], uploadUrl: 'http://example.com/upload', formData: {}, headers: { 'Content-Type': 'multipart/form-data' } } }, methods: { handleUploadSuccess (response, file, fileList) { // 上传成功后的处理逻辑 console.log(response) }, beforeUpload (file) { // 文件上传前的处理逻辑 console.log(file) } } } </script> ``` 3. 在组件实现文件上传的逻辑。在上传文件之前,需要设置请求头和请求数据,并且需要处理跨域请求。可以在组件的methods定义一个upload方法,用来发送上传请求。示例代码如下: ```vue <script> import axios from 'axios' import { Message } from 'element-ui' export default { name: 'FileUpload', data () { return { fileList: [], uploadUrl: 'http://example.com/upload', formData: {}, headers: { 'Content-Type': 'multipart/form-data' } } }, methods: { handleUploadSuccess (response, file, fileList) { // 上传成功后的处理逻辑 console.log(response) }, beforeUpload (file) { // 文件上传前的处理逻辑 console.log(file) }, upload () { let config = { headers: this.headers, withCredentials: true // 跨域请求需要设置withCredentials为true } let data = new FormData() data.append('file', this.fileList[0].raw) // 向后端发送上传请求 axios.post(this.uploadUrl, data, config) .then(response => { this.handleUploadSuccess(response) }) .catch(error => { console.log(error) }) } } } </script> ``` 4. 最后,在Vue组件使用El-upload组件,并且调用upload方法即可实现文件上传。示例代码如下: ```vue <template> <div> <el-upload class="upload-demo" :action="uploadUrl" :on-success="handleUploadSuccess" :before-upload="beforeUpload" :headers="headers" :data="formData" :file-list="fileList"> <el-button size="small" type="primary" @click="upload">点击上传</el-button> </el-upload> </div> </template> <script> import axios from 'axios' import { Message } from 'element-ui' export default { name: 'FileUpload', data () { return { fileList: [], uploadUrl: 'http://example.com/upload', formData: {}, headers: { 'Content-Type': 'multipart/form-data' } } }, methods: { handleUploadSuccess (response, file, fileList) { // 上传成功后的处理逻辑 console.log(response) }, beforeUpload (file) { // 文件上传前的处理逻辑 console.log(file) }, upload () { let config = { headers: this.headers, withCredentials: true // 跨域请求需要设置withCredentials为true } let data = new FormData() data.append('file', this.fileList[0].raw) // 向后端发送上传请求 axios.post(this.uploadUrl, data, config) .then(response => { this.handleUploadSuccess(response) }) .catch(error => { console.log(error) }) } } } </script> ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

胖鹅儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值