vue+netcore webapi下载excel文件

后端代码

      /// 前段下载Excel模板
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("DownLoadExcelModleSubSystemList")]
        //[YuebonAuthorize("DownLoadExcelModleSubSystemList")]
        public ActionResult DownLoadExcelModleSubSystemList()
        {
            string basedirectory = Path.GetDirectoryName(typeof(Program).Assembly.Location);

            //头部保存 文件名
            HttpContext.Response.Headers.Append("Content-Disposition", "filename=" + System.Web.HttpUtility.UrlEncode("menu权限导入模板.xls"));
            //文件类型
            FileExtensionContentTypeProvider provider = new FileExtensionContentTypeProvider();
            string memi;
            string fileFullName = basedirectory + @"/ExcelTemplate/menu权限导入模板.xls";

            string fileExtions = Path.GetExtension(fileFullName);
            //获取文件类型
            provider.Mappings.TryGetValue(fileExtions, out memi);
            //读取文件流
            FileStream fs = new FileStream(fileFullName, FileMode.Open, FileAccess.Read);
            
             return File(fs, memi, Path.GetFileName(fileFullName));
            
           
        }

  

  vue代码
    <el-button type="primary" size="mini" @click="downLoadMenuExcel2()">Controll Excel模板文件</el-button>

  

 

/**
   * 请求下载excel文件
   * @param data
   */
export function downloadMenuExcelTempalte() {
  return http.request({
    url: 'Menu/DownLoadExcelModleSubSystemList',
    method: 'post',
    responseType: 'blob',  // ‘不标记请求为blob获取的excel文件为乱码’
    baseURL: defaultSettings.apiSecurityUrl // 直接通过覆盖的方式
  })
}

  

  //下载excel模板文件
    downLoadMenuExcel2 () {
      this.$confirm('下载excel模板?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        downloadMenuExcelTempalte().then(res => {
          //我这里使用了拦截器进行了数据的整理 res=res.data
//未整理需要使用res.data进行数据接收 //方式一使用插件 //npm install js-file-download --save // fileDownload(res, 'xxx.xls', 'application/vnd.ms-excel') // 建立Blob对象,设置文件类型 //方式二使用自定义方法 const link = document.createElement('a') let blob = new Blob([res], { type: "application/vnd.ms-excel" }) let objectUrl = URL.createObjectURL(blob) // 建立URL link.href = objectUrl link.download = 'menu权限导入模板.xls' // 自定义文件名 link.click() // 下载文件 URL.revokeObjectURL(objectUrl); // 释放内存 }) }).catch(() => { // this.$message({ // type: 'info', // message: '已取消' // }); }) },

  

  

 

posted @ 2022-04-03 17:29  JohnnyLei  阅读(178)  评论(0)    收藏  举报