ASP.NET Web API 2 之文件下载

Ø  前言

目前 ASP.NET Web API 的应用非常广泛,主要承载着服务端与客户端的数据传输与处理,如果需要使用 Web API 实现文件下载,该clip_image001 实现呢,其实也是比较简单,以下示例用于下载安卓的 .apk 文件。

 

1.   C# 代码

/// <summary>

/// 获取最新 Apk 文件。

/// </summary>

/// <param name="request"></param>

/// <returns></returns>

[Route("getLatest"), HttpGet]

[AllowAnonymous]

public HttpResponseMessage GetLatest(HttpRequestMessage request)

{

    var appVersionInfo = appManageService.GetLatest();

    string vp = appVersionInfo.VersionPath;     //http://xxx.xxx.xx.xx:81/xxxxx/xxx/3.0.6_20171017181838121.apk

    int lastIndex = vp.LastIndexOf("/");

    string fileName = "Yoca_{0}".Fmt(vp.Substring(lastIndex + 1, vp.Length - (lastIndex + 1)));

 

    byte[] bytes = null;

    WebRequest webRequest = (WebRequest)HttpWebRequest.Create(vp);

    using (WebResponse webResponse = webRequest.GetResponse())

    {

        using (var stream = webResponse.GetResponseStream())

        {

            bytes = new byte[webResponse.ContentLength];

            stream.Read(bytes, 0, bytes.Length);

        }

    }

 

    var response = request.CreateResponse();

    response.Content = new ByteArrayContent(bytes ?? new byte[0]);

    response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(

        "application/vnd.android.package-archive");

    response.Content.Headers.ContentDisposition =

        new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")

    {

        FileName = fileName

    };

    return response;

}

 

2.   说明

1)   以上代码:首先,从数据库中读取最新的 .apk 文件路径(网络URI);然后,使用 WebRequest 等对象获取该文件的响应流;最后,将获取的 byte 数组转为 ByteArrayContent 对象,以响应 HTTP 消息。

2)   注意:需要根据不同的文件类型,设置响应的 ContentType 值,可参考:http://www.runoob.com/http/http-content-type.html

3)   其实,很多文件下载都是使用这种方式,比如导出 excel 或者 csv 文件等。

posted @ 2017-10-20 11:45  Abeam  阅读(795)  评论(0编辑  收藏  举报