Search code examples
c#httpamazon-s3blazorsftp

How to dynamically load images from an SFTP server in Blazor


I've just started with Blazor and I want to try and make a store/portofolio kind of site where one of the pages is a gallery (similar to Instagram's profiles). I'm planning on using AWS S3 to store the photos, but I can't seem to get the photos to be loaded correctly.

I'm also using SSH.NET to connect to the S3 server.

The HTML portion

<body>
    <div id="feed" class="centered">
        @for (int l = 0; l < @GetLineCount(); l++) //each line has a max of 5 images
        {
            <div class="feed-line">
                @for (int c = 0; c < 5; c++)
                {
                    <img src="@imagesPaths[@l * 5 + @c]" /> 
                }
            </div>
        }
    </div>
</body>

And for the C# portion

@code {
    public List<string> imagesPaths = new();

    protected override void OnInitialized()
    {
        var privateKey = new PrivateKeyFile(@"PATH TO KEY");
        using SftpClient client = new(serverUri, 22, username, privateKey);
        client.Connect();

        if (client.IsConnected)
        {
            var list = client.ListDirectory("bucket-name/gallery/"); //Correctly retrieves a list with all the files to be loaded

            foreach (var sftpFile in list)
            {
                imagesPaths.Add(sftpFile.FullName); //This would then be retrieved on the html portion
            }
        }
        client.Disconnect();
    }
}

My current problem is knowing how to convert the SFTP image URI to a HTTP image URI.

  • either by downloading it to wwwroot or
  • somehow exposing the S3 uploaded HTTP URL with authentication (since just the URL will retrieve access denied)

Solution

  • I do not know anything about Blazor.

    But in general:

    • Either download the files to the web server in your OnInitialized code. And make the <img src> URL point to those downloaded files.

      <img src="/some/temporary/path/on/server/image.jpg">
      
    • or make your <img src> URL point back to your web server to a script that will stream the individual file from the SFTP server to the web browser on the fly.

      <img src="some/script/on/server?download=image.jpg">
      

    Another option is Presigned S3 URLs.