AirNoir
AirNoir

Reputation: 251

Server call image from WebAPI

I have a intranet WebAPI server which provides services for a DMZ(internet) Server.

API actions:

[HttpGet]
public HttpResponseMessage ImagePath(string filePath)
{
    var result = new HttpResponseMessage(HttpStatusCode.OK);
    FileStream fileStream = new FileStream(filePath, FileMode.Open);
    Image image = Image.FromStream(fileStream);
    MemoryStream memoryStream = new MemoryStream();
    image.Save(memoryStream, ImageFormat.Jpeg);
    result.Content = new ByteArrayContent(memoryStream.ToArray());
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");

    return result;
}

The api does return an image sucessfully. I want to proceed a request from DMZ to intranet, but I don't know how to write the action, my code below:

public async Task<HttpResponseMessage> ImagePath(string filePath)
{ 
    HttpClientHandler handler = new HttpClientHandler()
    {
        UseDefaultCredentials = true,
    };

    using (var client = new HttpClient(handler)) {

        client.BaseAddress = new Uri(apiUrl); //apiUrl is my intranet domain
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("image/jpeg"));

        HttpResponseMessage fs = await client.GetAsync("cipap/api/baseapi/ImagePath?filePath=" + filePath);
        return fs;

    }

    //FileStream fs = new FileStream(filePath, FileMode.Open);
    //return File(fs, "image/jpeg");
}

Could somebody help me? Thanks a lot.

Upvotes: 3

Views: 1070

Answers (1)

AirNoir
AirNoir

Reputation: 251

I finally found the anwser ,
just make the action of a FileResult type, and return a file by:

File(fs.Content.ReadAsByteArrayAsync().Result, "image/jpeg");   

one more thing is that in the webapi action, I need to configure the filestream as below or the file will be locked after the first request:

FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);

public async Task<FileResult> ImagePath(string filePath)
{

    HttpClientHandler handler = new HttpClientHandler()
    {
        UseDefaultCredentials = true,
    };

    using (var client = new HttpClient(handler)) {

        client.BaseAddress = new Uri(apiUrl);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("image/jpeg"));
        HttpResponseMessage fs = await client.GetAsync("cipap/api/baseapi/ImagePath?filePath=" + filePath);

        return File(fs.Content.ReadAsByteArrayAsync().Result, "image/jpeg");               
    }

}

ref: Download file prompt when using WebAPI HttpResponseMessage

Upvotes: 1

Related Questions