WebAPI(三) 返回文件流、浏览器接收下载

WebAPI:

先从实际路径读取文件,并转换为二进制流,并构造ResponseMessage返回

public IHttpActionResult Get(string value)
{
     //实际路径
    string path = HttpContext.Current.Server.MapPath("~/temp");


    byte[] result = fileTobyte(path+ "/结果.xls");
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new StreamContent(new MemoryStream(result));
    response.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xls");
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName ="结果.xls",
    };

    return this.ResponseMessage(response);
}

前端接收:(vue2 uniapp):

主要是指定responseType: "arraybuffer"

 

this.$api.export().then(res => {

					const blob = new Blob([res.data], {
						type: 'application/vnd.ms-excel'
					});

					// 创建下载链接
					const url = window.URL.createObjectURL(blob);
					const link = document.createElement('a');
					link.href = url;
					link.setAttribute('download', '结果.xls'); // 设置文件名

					// 触发下载
					document.body.appendChild(link);
					link.click();

					// 清理
					document.body.removeChild(link);
					window.URL.revokeObjectURL(url);

					this.visible = false
				})

  

 

posted @ 2025-06-25 12:14  陈鹏昱Chen  阅读(26)  评论(0)    收藏  举报