How can I return Images from Web API in ASP.NET?


Hello,

I haven't used much of the Web API as of now, so I was thinking how can I return Web API from API controller in ASP.NET?

Any Code sample, links?

Thanks


Asked by:- neena
1
: 18060 At:- 4/11/2018 8:57:34 AM
C# Web API return image from web api in asp.net







2 Answers
profileImage Answered by:- Vinnu

In .NET WEB API 2/1

You can return Image from ASP.NET Web API using HttpResponseMessage in C# APIController, something like below example:

    public HttpResponseMessage GetImage(int id)
    {
      ImageDbContext db = new ImageDbContext();
      var data = from i in db.Images
                 where i.Id == id
                 select i;

      Image img = (Image)data.SingleOrDefault();
      byte[] imgData = img.ImageData;
      MemoryStream ms = new MemoryStream(imgData);
      HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
      response.Content = new StreamContent(ms);
      response.Content.Headers.ContentType = new 
      System.Net.Http.Headers.MediaTypeHeaderValue("image/png");

       //send response of image/png type
      return response;
    }

In the above method,  return type of GetImage() method is HttpResponseMessage. The HttpResponseMessage class from System.Net.Http represents an HTTP response that includes the HTTP status code and the response data. The GetImage() method accepts an Image id that is to be retrieved. Inside, it fetches the Image from the database and puts the ImageData in a byte array. A new MemoryStream is then created based on this byte array.

In .NET Core

[HttpGet]
public IActionResult Get()
{            
    Byte[] b = System.IO.File.ReadAllBytes(@"E:\\FileName.png");   // You can use your own method over here.         
    return File(b, "image/png");
}

In .NET Core, you don't need to create "HttpResponseMessage" to return images from API, it will not return you data, also it will not throw any error, you have to use File() method directly inside the Controller.

OR

In .NET Core Web API

   [HttpGet]
    public IActionResult Get(int imageId)
    {            
       return PhysicalFile(@"C:\yourImage.jpg", "image/jpeg");
    }

PhysicalFile helps to return file from Asp.Net Core WebAPI easily.

4
At:- 4/13/2018 11:08:54 AM Updated at:- 11/15/2022 7:52:27 AM
Thanks 0
By : neena - at :- 4/22/2018 12:21:32 PM


profileImage Answered by:- Sam

You can also download a file from .NET Web API using <a href>, here is the example

<a href='/APIURL/DownloadFile?fileName=ImageName.jpg'>Download Image</a>

and in your C# WEB API you can create the method

[HttpGet]
public HttpResponseMessage DownloadFile(string fileName)
{
	if (!string.IsNullOrEmpty(fileName))
	{
		string filePath = "/images/";
		string fullPath = AppDomain.CurrentDomain.BaseDirectory + filePath + "/" + fileName;
		if (File.Exists(fullPath))
		{

			HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
			var fileStream = new FileStream(fullPath, FileMode.Open);
			response.Content = new StreamContent(fileStream);
			response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
			response.Content.Headers.ContentDisposition.FileName = fileName;
			return response;
		}
	}

	return new HttpResponseMessage(HttpStatusCode.NotFound);
}

 Basically, the API will accept a query string which is the file name. We can get the root path of our project by using the following code.

AppDomain.CurrentDomain.BaseDirectory

then you need to make sure if the user has passed the file name in the query string and if they are present on server, using System.IO.File to see we check if the file exists on the server, if yes return it, otherwise throw error, file not found error.

1
At:- 6/4/2018 11:58:39 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use