下載文件到本地是很多項目開發(fā)中需要實現(xiàn)的一個很簡單的功能。說簡單,是從具體的代碼實現(xiàn)上來說的,.NET的文件下載方式有很多種,本示例給大家介紹的是ASP.NET Web Api方式返回HttpResponseMessage下載文件到本地。實現(xiàn)的方法很簡單,其中就是讀取服務器的指定路徑文件流,將其做為返回的HttpResponseMessage的Content。直接貼出DownloadController控件器的代碼:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
namespace DownloadFileFromWebApi.Controllers
{
[RoutePrefix("download")]
public class DownloadController : ApiController
{
[Route("get_demo_file")]
public HttpResponseMessage GetFileFromWebApi()
{
try
{
var FilePath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/download/EditPlus64_xp85.com.zip");
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="Wep Api Demo File.zip"
};
return response;
}
catch
{
return new HttpResponseMessage(HttpStatusCode.NoContent);
}
}
}
}
實現(xiàn)以上控制器后,我們可以直接打開這個api的地址(示例中的地址為:http://localhost:60560/download/get_demo_file),即可彈出下載文件的對話框了,如圖: asp-net-web-api-download-file 當然,也可以直接通過示例項目首頁的下載鏈接體驗,點擊“下載示例文件”按鈕,將會彈出保存文件的提示。 好了,示例比較簡單,不用多說了。點擊這里下載示例源碼。
以上就是本文的全部內(nèi)容,希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:- C# web api返回類型設置為json的兩種方法
- C#中通過API實現(xiàn)的打印類 實例代碼
- C#實現(xiàn)快遞api接口調(diào)用方法
- C#通過WIN32 API實現(xiàn)嵌入程序窗體
- 使用C#調(diào)用系統(tǒng)API實現(xiàn)內(nèi)存注入的代碼
- c#調(diào)用api控制windows關機示例(可以重啟/注銷)
- C#利用win32 Api 修改本地系統(tǒng)時間、獲取硬盤序列號
- C#獲取USB事件API實例分析
- c#之利用API函數(shù)實現(xiàn)動畫窗體的方法詳解
- C# API中模型與它們的接口設計詳解