? preface
At present, the application of ASP is very extensive, which mainly carries the data transmission and processing between server and client, if need to use Web API to implement file download, the implementation is In fact, it is also relatively simple, the following example is used to download the . apk file for Android.
1. C # Code
/// <summary>
/// Get the latest Apk file.
/// </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
< Span lang= "en-US" style= "font-family:; Color: "> int " Span lang= "en-US" style= "font-family:; Color: "> LastIndex = VP." LastIndexOf ( "/" ";
string fileName = "yoca_{0}". FMT (VP. Substring (LastIndex + 1, VP. Length-(LastIndex + 1)));
< Span lang= "en-US" style= "font-family:; Color: "> byte " Span lang= "en-US" style= "font-family:; Color: ">[" bytes = null ;
< Span lang= "en-US" style= "font-family:; Color: "> webrequest WebRequest = ( webrequest " httpwebrequest
using (webresponse WebResponse = Webrequest.getresponse ())
{
using (var stream = WebResponse.GetResponseStream ())
{
Bytes = new byte[webresponse.contentlength];
Stream. Read (bytes, 0, bytes. Length);
}
}
< Span lang= "en-US" style= "font-family:; Color: "> var " Span lang= "en-US" style= "font-family:; Color: "> response = Request. Createresponse ();
< Span lang= "en-US" style= "font-family:; Color: "> 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;
}
< Span lang= "en-US" style= "font-family:" > 2. description
< Span lang= "en-US" style= "font-family:" > 1) above code: first, read the latest .apk file path from the database (network uri ), then use webrequest byte array to bytearraycontent object in response to HTTP The message.
2) Note: The ContentType value of the response needs to be set according to different file types, for reference:http://www.runoob.com/http/ http-content-type.html
3) In fact, many file downloads are used in this way, such as exporting Excel or csv files.
ASP. NET Web API 2 File download