标签:
WebApi下载附件文件
1.
[RoutePrefix("down")] public class FilesController : ApiController { [GET("file/{id}")] public HttpResponseMessage GetSomePdf(string id) { var path = MyApp.PathToSomePdf(id); if (path!= null) return FileAsAttachment(path, "somepdf.pdf"); return new HttpResponseMessage(HttpStatusCode.NotFound); } public static HttpResponseMessage FileAsAttachment(string path, string filename) { if (File.Exists(path)) { HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); var stream = new FileStream(path, FileMode.Open); result.Content = new StreamContent(stream); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = filename; return result; } return new HttpResponseMessage(HttpStatusCode.NotFound); }
2.
public class DataController : ApiController { // Sample content used to demonstrate range requests private static readonly byte[] _content = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Content/airports.csv")); // Content type for our body private static readonly MediaTypeHeaderValue _mediaType = MediaTypeHeaderValue.Parse("text/csv"); public HttpResponseMessage Get(bool IsLengthOnly) { //if only length is requested if (IsLengthOnly) { return Request.CreateResponse(HttpStatusCode.OK, _content.Length); } else { MemoryStream memStream = new MemoryStream(_content); // Check to see if this is a range request (i.e. contains a Range header field) if (Request.Headers.Range != null) { try { HttpResponseMessage partialResponse = Request.CreateResponse(HttpStatusCode.PartialContent); partialResponse.Content = new ByteRangeStreamContent(memStream, Request.Headers.Range, _mediaType); return partialResponse; } catch (InvalidByteRangeException invalidByteRangeException) { return Request.CreateErrorResponse(invalidByteRangeException); } } else { // If it is not a range request we just send the whole thing as normal HttpResponseMessage fullResponse = Request.CreateResponse(HttpStatusCode.OK); fullResponse.Content = new StreamContent(memStream); fullResponse.Content.Headers.ContentType = _mediaType; return fullResponse; } } } }
标签:
原文地址:http://www.cnblogs.com/mxm2005/p/4881759.html