vue实现文件下载功能

对于Vue中实现一般的下载功能很简单,一般为了方便,在项目文件的api.js配置文件中添加一个下载方法即可,这里以以下download方法为例。将download这部分方法添加到api.js文件中即可。

api.js配置

export default {
//   下载关键代码
  download(url, params) {
    return new Promise((resolve, reject) => {
        axios({
        //   和后端协商好下载方法post/get?
        method: 'Post',
        url: baseUrl + url,
        data: params,
        headers: {
            'Content-Type': 'application/json',
            // 设置请求头携带的token
          token: JSON.parse(localStorage.getItem('userInfo')).token,
        },
        responseType: 'blob',
      })
        .then((res) => {
          console.log(res);
          const fileName = res.headers['content-disposition'].split('filename=')[1];
          const response = res.data;
          const r = new FileReader();
          r.onload = () => {
            try {
              const resData = JSON.parse(this.result);
              if (resData) {
                if (resData.error_no === undefined) {
                  throw new Error('解析成功!');
                } else if (resData.error_no !== '0') {
                  Message({
                    message: resData.error_info || 'Error',
                    type: 'error',
                    duration: 5 * 1000,
                  });
                }
              }
            } catch (err) {
              // 兼容ie11
              if (window.navigator.msSaveOrOpenBlob) {
                try {
                  const blobObject = new Blob([response]);
                  window.navigator.msSaveOrOpenBlob(blobObject, fileName);
                } catch (e) {
                  console.log(e);
                  reject(e);
                }
                return;
              }
              const url = window.URL.createObjectURL(new Blob([response]));
              const link = document.createElement('a');
              link.style.display = 'none';
              link.href = url;
              link.setAttribute('download', fileName);
              document.body.appendChild(link);
              link.click();
            }
          };
          r.readAsText(response);
          resolve();
        })
        .catch((error) => {
          console.log(error);
          Message({
            message: '下载失败!',
            type: 'error',
            duration: 5 * 1000,
          });
          reject(error);
        });
    });
  },
};

Vue实例中使用该方法。使用方式和get和post、put等接口请求方式一样。
<template>
  <div class="contain">
    <div class="tableArea">
      <el-table v-loading="loading" :data="tableData" stripe>
        <!-- <template slot="empty" slot-scope="scope">
          <p>sadssadssadsadsdsadsa</p>
        </template> -->
        <el-table-column type="index" label="序号" width="100"></el-table-column>
        <el-table-column prop="fileOrgName" label="名称" min-width="180">
          <template slot-scope="scope">
                                       触发下载函数
            <div @click="downloadHandler(scope.row)">
              <p style="color:#4880ff;cursor: pointer;">{{ scope.row.fileOrgName }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="数据日期" min-width="180">
          <template slot-scope="scope">
            <div>
              {{ scope.row.createTime | createformat() }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="remainDay" label="数据表类型" min-width="180">
        </el-table-column>
        <el-table-column prop="updateTime" label="上传时间" min-width="180">
          <template slot-scope="scope">
            <div>
              {{ scope.row.updateTime | updateformat() }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createUserName" label="上传人" min-width="180"></el-table-column>
      </el-table>

      <pagination :size="page.pageSize" :current="page.current" :total="page.total" @currentChange="handleCurrentChange" @sizeChange="handleSizeChange" />
    </div>
    <tips :dialogVisible="tipsVisible" @on-cancel="tipsVisible = false" @on-ok="enterCover"></tips>
  </div>
</template>
<script>
import moment from 'moment';
import tips from '../../components/tips';

export default {
  filters: {
    createformat(val) {
      return moment(val).format('YYYY/MM/DD');
    },
    updateformat(val) {
      return moment(val).format('MM/DD HH:mm');
    },
  },
  components: {
    tips,
  },
  data() {
    return {
      fileList: [],
      tableData: [],
      fileAgain: null,
      loading: false,
      tipsVisible: false,
      page: {
        total: 1,
        current: 1,
        pageSize: 5,
      },
    };
  },
  created() {
    this.readExcel();
  },
  methods: {
    // 下载当前表单,使用方式和get和post、put等接口请求方式一样
    downloadHandler(val) {
      this.$api.download(`/file/downloadFile?fileId=${val.id}`).then((res) => {
        console.log(res);
      });
    },
  },
};
</script>


已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页