-1

i am creating web Api for retrieve image from server folder,in c# , i need code for that, thanks in advance,

[HttpPost]
[Route("Fileretrive")]
public void retrive(string filename)
{
    //var ctx = HttpContext.Current;
    var root = HttpContext.Current.Server.MapPath("~/Photos");
    var tempath = Path.Combine(root,filename);
    Directory.GetFiles(tempath);
    byte[] byteArray = null;
    byteArray = System.IO.File.ReadAllBytes(tempath);

}
4
  • what is the error your facing? Commented Dec 6, 2019 at 6:27
  • Does this answer your question? How to to return an image with Web API Get method Commented Dec 6, 2019 at 10:01
  • Btw, POST is used to send data to a server and GET is for requesting data from a specified resource. 2/. Your method return void. Commented Dec 6, 2019 at 10:03
  • @JagadeeshGovindaraj i cant return File Commented Dec 6, 2019 at 10:09

1 Answer 1

0

you are nearly there. first you need to return the action result. since you are streaming byte, use file as your return.

[HttpPost]
[Route("Fileretrive")]
public IActionResult retrive(string filename)
{
    //var ctx = HttpContext.Current;
    var root = HttpContext.Current.Server.MapPath("~/Photos");
    var tempath = Path.Combine(root,filename);
    Directory.GetFiles(tempath);
    byte[] byteArray = null;
    byteArray = System.IO.File.ReadAllBytes(tempath);
    // check your mime type, and set your unique file name. maybe use DateTime for your file name
    return File(byteArray , "image/jpeg", $"{DateTime.Now.ToString("ddMMMyyyy")}.jpeg"); 

}
Sign up to request clarification or add additional context in comments.

6 Comments

while return File, i got an error 'System.IO.File' is a type but used like a variable
typo it should be byteArray instead of buffer
IActionResult i got an error,the type or namespace name IActionResult could not be found
@SanThoShKumar, use the light bulb on the type to get the using. should be Microsoft.AspNetCore.Mvc.
i am creating web Api not mvc
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.