下載文件到本地是很多項(xiàng)目開(kāi)發(fā)中需要實(shí)現(xiàn)的一個(gè)很簡(jiǎn)單的功能。說(shuō)簡(jiǎn)單,是從具體的代碼實(shí)現(xiàn)上來(lái)說(shuō)的,.NET的文件下載方式有很多種,本示例給大家介紹的是ASP.NET Web Api方式返回HttpResponseMessage下載文件到本地。實(shí)現(xiàn)的方法很簡(jiǎn)單,其中就是讀取服務(wù)器的指定路徑文件流,將其做為返回的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);
}
}
}
}
實(shí)現(xiàn)以上控制器后,我們可以直接打開(kāi)這個(gè)api的地址(示例中的地址為:http://localhost:60560/download/get_demo_file),即可彈出下載文件的對(duì)話框了,如圖: asp-net-web-api-download-file 當(dāng)然,也可以直接通過(guò)示例項(xiàng)目首頁(yè)的下載鏈接體驗(yàn),點(diǎn)擊“下載示例文件”按鈕,將會(huì)彈出保存文件的提示。 好了,示例比較簡(jiǎn)單,不用多說(shuō)了。點(diǎn)擊這里下載示例源碼。
以上就是本文的全部?jī)?nèi)容,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:- C# web api返回類型設(shè)置為json的兩種方法
- C#中通過(guò)API實(shí)現(xiàn)的打印類 實(shí)例代碼
- C#實(shí)現(xiàn)快遞api接口調(diào)用方法
- C#通過(guò)WIN32 API實(shí)現(xiàn)嵌入程序窗體
- 使用C#調(diào)用系統(tǒng)API實(shí)現(xiàn)內(nèi)存注入的代碼
- c#調(diào)用api控制windows關(guān)機(jī)示例(可以重啟/注銷)
- C#利用win32 Api 修改本地系統(tǒng)時(shí)間、獲取硬盤序列號(hào)
- C#獲取USB事件API實(shí)例分析
- c#之利用API函數(shù)實(shí)現(xiàn)動(dòng)畫窗體的方法詳解
- C# API中模型與它們的接口設(shè)計(jì)詳解