Wednesday, 5 April 2017

Download file from an ASP.NET Web API method using C#

[HttpGet]
        [ResponseType(typeof(void))]
        public async Task<IHttpActionResult> DownloadFileAsync(inputmodel context)
        {
            HttpResponseMessage result = null;
             var documentDownload = await _documentManager.DownloadFileAsync(context);

//After getting byte array from below function we will pass to MemoryStream and this MemoryStream add to HttpResponseMessage

                if (documentDownload != null)
                {
                    var stream = new MemoryStream(documentDownload);
                    result = Request.CreateResponse(HttpStatusCode.OK);
                    result.Content = new StreamContent(stream);
                    result.Content.Headers.ContentType =
                        new MediaTypeHeaderValue("pdf");
                    result.Content.Headers.ContentDisposition =
                        new ContentDispositionHeaderValue("attachment")
                        {
                            FileName = string.Concat(FileName, ".", "pdf")
                        };
                }
                else
                {
                    result = Request.CreateResponse(HttpStatusCode.NoContent);
                }
            }
            return ResponseMessage(result);
        }


        Note => Below method is going to convert file into byte array    

public async Task<byte[]> DownloadFileAsync(ModelClass context)
        {
            string filepath = "Your Server path or local path" + @"\\" + context.Id + @"\\" + context.Guid + @"." + "pdf";
            var directorypath = "Your server path or local path" + @"\\" + context.Id;
            if (!Directory.Exists(directorypath)) return null;
            if (!File.Exists(filepath)) return null;
            var bytes = await Task.Run(() => File.ReadAllBytes(filepath));
            return bytes;
        }

No comments:

Post a Comment