zoukankan      html  css  js  c++  java
  • 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 文件等。

  • 相关阅读:
    MySQL:批量修改表的排序规则
    Python黑客编程3网络数据监听和过滤
    springboot redis 项目实战 完整篇
    C#读取U盘序列号
    AS3,ReferenceError: Error #1056: 无法为 ×× 创建属性 ×××。
    知道挖掘机如何从货车上下来吗?
    一次进销存软件架构的实践(二)——业务外观层设计
    重构你的软件企业
    遇到了火狐扩展全部丢失的问题
    分布式系统设计原理与方案
  • 原文地址:https://www.cnblogs.com/abeam/p/7698726.html
Copyright © 2011-2022 走看看