Guest User

Untitled

a guest
Jun 13th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. [AllowAnonymous]
  2. [HttpGet]
  3. [Route("DownloadImage")]
  4. public HttpResponseMessage DownloadFile(string fileName)
  5. {
  6.  
  7. string filePath = Properties.Settings.Default.Path;
  8. string fullPath = filePath + fileName;
  9.  
  10. try
  11. {
  12. //Check if the file exists. If the file doesn't exist, throw a
  13. file not found exception
  14. if (!File.Exists(fullPath))
  15. {
  16. throw new HttpResponseException(HttpStatusCode.NotFound);
  17. }
  18.  
  19. //Copy the source file stream to MemoryStream and close the filestream
  20. MemoryStream responseStream = new MemoryStream();
  21. Stream fileStream = File.Open(fullPath, FileMode.Open);
  22.  
  23. fileStream.CopyTo(responseStream);
  24. fileStream.Close();
  25. responseStream.Position = 0;
  26.  
  27. HttpResponseMessage response = new HttpResponseMessage();
  28. response.StatusCode = HttpStatusCode.OK;
  29.  
  30. //Write the memory stream to HttpResponseMessage content
  31. response.Content = new StreamContent(responseStream);
  32. string contentDisposition = string.Concat("attachment;
  33. filename=", fileName);
  34. response.Content.Headers.ContentDisposition =
  35. ContentDispositionHeaderValue.Parse(contentDisposition);
  36. response.Content.Headers.ContentType =
  37. new MediaTypeHeaderValue("image/jpeg");
  38. return response;
  39. }
  40. catch
  41. {
  42. throw new
  43. HttpResponseException(HttpStatusCode.InternalServerError);
  44. }
  45. }
Add Comment
Please, Sign In to add comment