I am using ASP.NET Web API.
I want to download a PDF with C# from the API (that the API generates).
Can I just have the API return a byte[]
? and for the C# application can I just do:
byte[] pdf = client.DownloadData("urlToAPI");?
and
File.WriteAllBytes()?
Users can either left-click a download link to download the file or right-click the link to choose “ Save Link As ” in the context menu and save the file.
So, if you want to return a View you need to use the simple ol' Controller . The WebApi "way" is like a webservice where you exchange data with another service (returning JSON or XML to that service, not a View). So whenever you want to return a webpage ( View ) for a user you don't use the Web API.
Better to return HttpResponseMessage with StreamContent inside of it.
Here is example:
public HttpResponseMessage GetFile(string id) { if (String.IsNullOrEmpty(id)) return Request.CreateResponse(HttpStatusCode.BadRequest); string fileName; string localFilePath; int fileSize; localFilePath = getFileFromID(id, out fileName, out fileSize); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read)); response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentDisposition.FileName = fileName; response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); return response; }
UPD from comment by patridge: Should anyone else get here looking to send out a response from a byte array instead of an actual file, you're going to want to use new ByteArrayContent(someData) instead of StreamContent (see here).
I made the follow action:
[HttpGet] [Route("api/DownloadPdfFile/{id}")] public HttpResponseMessage DownloadPdfFile(long id) { HttpResponseMessage result = null; try { SQL.File file = db.Files.Where(b => b.ID == id).SingleOrDefault(); if (file == null) { result = Request.CreateResponse(HttpStatusCode.Gone); } else { // sendo file to client byte[] bytes = Convert.FromBase64String(file.pdfBase64); result = Request.CreateResponse(HttpStatusCode.OK); result.Content = new ByteArrayContent(bytes); result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = file.name + ".pdf"; } return result; } catch (Exception ex) { return Request.CreateResponse(HttpStatusCode.Gone); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With