Downloading files to the local area is a very simple feature that needs to be implemented in many project development. Say simple, is from the concrete code realization comes up to say,. NET file Download Way There are many kinds, this example is to introduce the ASP.net Web API way to return httpresponsemessage download file to local. The method of implementation is simple, which is to read the server's specified path file stream as the content of the returned httpresponsemessage. The code that directly pastes the Downloadcontroller control device:
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 = S Ystem.
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);
}
}
}
}
After implementing the above controller, we can directly open the address of this API (the example of the address is: http://localhost:60560/download/get_demo_file), you can pop up the download file dialog box, as shown: Asp-net-web-api-download-file of course, you can also directly through the sample project home download link experience, click the "Download sample Files" button, will pop up to save the file prompts. Well, the example is simpler, needless to say. Click here to download the sample source code.
The above is the entire content of this article, I hope to give you a reference, but also hope that we support the cloud habitat community.