Vue axios 实现文件下载

Vue axios 实现文件下载,第1张

一、.net core 下载接口示例
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.IO;
using System.Data;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.StaticFiles;
using System.Text;
using System.Web;
using Newtonsoft.Json;

namespace Cari.secda.Web.Controllers
{
    /// 
    /// 文件处理(导入/导出/下载)
    /// 
    [Route("api/file/[action]")]
    [ApiController]
    public class FileApiController : IbpApiControllerBase
    {
        private IHostingEnvironment environment;
        private readonly IMapper mapper;
        public FileApiController(IMapper mapper, IHostingEnvironment _environment)
        {
            this.mapper = mapper;
            this.environment = _environment;
        }
        /// 
        /// 下载模板文件
        /// 
        /// 模板类别 1:人员资质证书 2:风险基元 
        /// 
        [HttpGet]
        public IActionResult DownloadTemplateFile(string fileType)
        {
            try
            {
                string webRootPath = environment.ContentRootPath + "\\TemplateFiles\\";
                var filePath = "";
                if (fileType == "1")
                {
                    filePath = webRootPath + "安全资格证导入模板.xlsx";
                }
                else if (fileType == "2")
                {
                    filePath = webRootPath + "风险基元库导入模板.xlsx";
                }
                var stream = System.IO.File.OpenRead(filePath);
                string fileExt = Path.GetExtension(filePath);
                //获取文件的ContentType
                var provider = new FileExtensionContentTypeProvider();
                var memi = provider.Mappings[fileExt];
                return File(stream, memi, Path.GetFileName(filePath));
            }
            catch (Exception ex)
            {
                return NotFound();
            }
        }
    }
}
二、vue axios 接口调用封装js

request.js代码示例

import axios from 'axios'
import { Message, Notification } from 'element-ui'
import Cookies from 'js-cookie'
let userToken = Cookies.get('user_token')
if(userToken === undefined || userToken === ''){
  userToken = '554db1d4-99f2-44e6-aae8-c0179896f013'
}

console.log(process.env.VUE_APP_BASE_API,'VUE_APP_BASE_API----')
axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
axios.defaults.headers['UserId'] = userToken

const service = axios.create({
  baseURL: 'http://192.168.1.214/secda' , // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 1000*60*5 // request timeout
})
// 请求拦截 可在请求头中加入token等
service.interceptors.request.use(
  (config) => {
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
// 响应拦截 对响应消息作初步的处理
service.interceptors.response.use(
  (resp) => {
    // alert(JSON.stringify(resp))
    // console.log(resp,'-------',resp.config.responseType)
    if (resp.data && resp.config.responseType != "blob") {
      localStorage.UserId=resp.config.headers.UserId
      // console.log(resp.data)
      if (resp.data.code !== 1) {
        // console.log(resp.status)
        Message({
          type: 'error',
          message: resp.data.message || resp.data.message,
          duration: 3000
        })
      }
      return {
        code: resp.data.code,
        data: resp.data.data,
        msg: resp.data.message
      }
    } else {
      return resp.data
    }
  },
  (error) => {
    const originalRequest = error.config
    if (
      error.code === 'ECONNABORTED' &&
      error.message.includes('timeout') &&
      !originalRequest._retry
    ) {
      Message({ type: 'error', message: '请求超时,请刷新页面' })
      return Promise.reject(new Error('请求超时,请刷新页面'))
    }
    if (error.response) {
      switch (error.response.states) {
        case 400: {
          if (
            error.response &&
            error.response.data &&
            error.response.data.msg
          ) {
            Notification.error({
              title: '400错误',
              message: error.response.data.msg,
              duration: 3000,
              closable: true
            })
          }
          break
        }
      }
    }
  }
)

export default service
三、接口调用示例

common.js

import request from "@/utils/request.js";

//下载模板
export function getDownloadfile(params) {
  return request({
    url: "/api/file/downloadTemplateFile",
    method: "get",
    responseType:"blob",
    params
  });
}
四、页面代码实现



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1322889.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-12
下一篇2022-06-12

发表评论

登录后才能评论

评论列表(0条)

    保存