user240181
user240181

Reputation: 83

How can I show image file from Amazon S3 in asp.net mvc?

I need to show image(thumbnail) in view page using controller/action.(like: /Image/Thumbnail) I can send image file that is stored locally by calling the method in controller.

// sample code
public FileResult Thumbnail()
{
    // get image
    Stream outFile = System.IO.File.Open("c:\\test.jpg", FileMode.Open);

    // send image
    return File(outFile, "image/jpeg");
}

How can I send image file that is stored in Amazon S3 ?

Can I use Amazon S3 URL in the above method to return image ? --> http://bucketname.s3.amazonaws.com/test.jpg?AWSAccessKeyId=AKIAIDLH65EJ6LSWERDF&Expires=1266497098&Signature=lopDEDErjNLy2uz6X6QCNlIjkpB0%3D

Upvotes: 7

Views: 5666

Answers (4)

Hosuing
Hosuing

Reputation: 1

public async Task<YourModelImages> GetImgById(int imgId)
 {
     using var dc = DataContext();
     return await dc.YourModelImages.FirstOrDefaultAsync(i => i.Id == imgId);
 }


   [Route("show-img")]
   [AllowAnonymous]
   public async Task<IActionResult> ShowImg(int imgId)
   {
       var img = await _Service.GetImgById(imgId);
       if (img == null)
       {
           return NotFound();
       }

     

       var byts = await AppService.FileReadService.ReadFileAsync(img.Url);
       return File(byts, img.Url.FileContentType());
   }

Razor Page :

 @foreach (var img in Model.Files)
 {
     <div class="col-sm-3">
         <img src="@Url.Action("ShowImg", "Controller", new {imgId = img.Id})" class="img-responsive img-thumbnail" />
     </div>
 }

Upvotes: 0

Pharabus
Pharabus

Reputation: 6062

you can make a webrequest to get the stream

public FileResult Thumbnail()
    {
        // get image
        HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(@"http://bucketname.s3.amazonaws.com/test.jpg?AWSAccessKeyId=AKIAIDLH65EJ6LSWERDF&Expires=1266497098&Signature=lopDEDErjNLy2uz6X6QCNlIjkpB0%3D");
        WebResponse myResp = myReq.GetResponse();

        Stream outFile = myResp.GetResponseStream();

        // send image
        return File(outFile, "image/jpeg");
    }

Upvotes: 1

Pbirkoff
Pbirkoff

Reputation: 4702

Try loading the image with a WebClient:

WebClient wClient = new WebClient();
Stream stream = new MemoryStream(wClient.DownloadData('http://....jpg'));

return File(stream, "image/jpg");

Upvotes: 1

PanJanek
PanJanek

Reputation: 6675

You can return a redirect result:

public ActionResult Thumbnail()
{
    return Redirect("http://domain.com/test.jpg");
}

If the url points at the image file then it will work. Of course you shouldn't present the url of this action to user but use it in some other view as <img> src attribute value:

<img src="<%= Url.Action("Thumbnail", "ControllerName") %>" />

Upvotes: 4

Related Questions