Search code examples
imagefileasp.net-web-apipathgetfiles

How to make a path to a Web Api method


I want to write a method that can dynamically send a folder path and then send an image file to the client.

The code is static

[Route("GetImageFile/{id}")]
[HttpGet]
public HttpResponseMessage GetImageFile(string id)
{
    var response = new HttpResponseMessage(HttpStatusCode.OK);
    FileStream stream = new FileStream(@"d:\gate\images\" + @"\" + id + ".jpg", 
                 System.IO.FileMode.Open);
    response.Content = new StreamContent(stream);
    response.Content.Headers.ContentType = 
                 new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
    return response;
}

Now I want to take the episode @ "d: \ gate \ images \" dynamically from the client.


Solution

  • I think taking second action argument from uri will solve your issue, but such approach, however, isn't fully restful. Example:

    [Route("GetImageFile/{id}")]
    [HttpGet]
    public HttpResponseMessage GetImageFile([FromUri] string id, [FromUri] string searchIn = @"d:\gate\images\") //d:\gate\images\ as default path
    {
        var response = new HttpResponseMessage(HttpStatusCode.OK);
        FileStream stream = new FileStream(searchIn + @"\" + id + ".jpg", 
                     System.IO.FileMode.Open);
        response.Content = new StreamContent(stream);
        response.Content.Headers.ContentType = 
                     new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
        return response;
    }
    

    And you can call this like:

    Get GetImageFile/myfileId?searchIn=c:\pub //P.S. Don't forget about URL encoding and security