Webapi之文件下载

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Song_Lynn/article/details/79645411

Webapi之文件下载

该方法有问题!!!直接输入api没有问题,但是用axios调用api则下载的excel没有内容,如果是直接点击a标签(标签href值为api)也没问题

范例说明:

  • 前端:vue.js + element-ui
  • 后端:c# webapi
  • 其它:只尝试本地调试,未在服务器上验证

前端部分

// html
<el-button
          size="mini" round
          icon="el-icon-download"
          @click="downloadExcel">导出</el-button>

// 引用外部js文件,在exprot default{}前
import EXCEL from '../../common/HandleExcel.js'
// 调用api
downloadTemplate: function () {
        this.axios.get(this.docApi + '/template?filename=StudentTemplate.xlsx', {
          responseType: 'blob'
        }).then((res)=>{
          EXCEL.downloadFile(res, '学生信息导入模板');
        },(res)=>{
          console.log(res);
        });
      }

// 外部js文件,HandleExcel.js
const EXCEL = {
  downloadFile: function (data, fileName) {
    if(!data){
      return;
    }
    let url = window.URL.createObjectURL(new Blob([data]));
    let link = document.createElement('a');
    link.style.display = 'none';
    link.href = url;
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
}
export default EXCEL;

后端部分

[RoutePrefix("api/handledoc")]
    public class HandleDocumentController : ApiController
    {
        static string fileUrl = @"/document/";  //文件路径
        //  api/handledoc/template?filename={...}
                [Route("template")]
                [HttpGet]
                public HttpResponseMessage getDocTemplate(string filename)
                {
                    var FilePath = System.Web.Hosting.HostingEnvironment.MapPath(fileUrl + filename);     //获取完整绝对路径
                    var stream = new FileStream(FilePath, FileMode.Open);
                    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                    response.Content = new StreamContent(stream);
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = HttpUtility.UrlEncode(Path.GetFileName(FilePath))
                    };
                    return response;
                }
    }

猜你喜欢

转载自blog.csdn.net/Song_Lynn/article/details/79645411
今日推荐