Search code examples
imageasp.net-web-apistreamfilestream

Need to display an image retrieved from WebApi call


I need to display an image as if using normal HTML, but I can't provide a normal url to the image for security reasons. Instead I need to retrieve the image from a WebApi service. I found this:

https://stackoverflow.com/a/24985886/1481314

And, I've looked at the links provided in the answers, but something isn't working. All I'm getting is a missing image placeholder.

This is my code - client-side:

     angular.element('#' + imageType + '_' + itemID).html('<img src="/api/filemanagermaindata/getFile?systemName=' + baseData.CustomerData.SystemName + '&fileID=' + id + '" />')

This is my WebApi Controller Method

[HttpGet]
[Route("api/filemanagermaindata/getFile")]
public HttpResponseMessage GetFile(string systemName, int fileID)
{
    var customerData = ValidateUser(systemName, 0);
    var response = this.fileMover.GetFileDataHttpResponse(customerData.OrganizationID, fileID);
        return response;
}        

And my class method that gets and returns the image...

var response = new HttpResponseMessage();

try
{
    FileManagerItem item = this.dataService.GetFileByID(fileID);
    var fullPath = this.rootLocation + Path.Combine( item.PhysicalPath, item.Name);

if (!File.Exists(fullPath))
{
    throw new Exception("Unable to locate the requested file");
}

var fileType = Path.GetExtension(item.Name).Replace(".", string.Empty);

if (ApplicationSettings.Instance.ImageFileExtensions.Contains(fileType))
{
    fileType = string.Format("image/{0}", fileType);
}

using (FileStream fileStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read))
{
    response = new HttpResponseMessage { Content = new StreamContent(fileStream) };
    response.Content.Headers.ContentType = new MediaTypeHeaderValue(fileType);
    response.Content.Headers.ContentLength = fileStream.Length;
};

return response;
}

Solution

  • Dumb mistake. The using {} block was killing the FileStream before the data was loaded.