Loading image from remote server in different LAN

2019-09-16 17:40发布

My stack is ASP.NET (Nancy) with Razor view engine. But this may concern all technologies I suppose.
I have two LAN networks (let's call them Large network and Small network) and two servers (a.k.a Main server and Image server). Main server can be reached by computers from both networks but Image server is visible only for machines in Small network. I have website served by Main server which shows images from remote (Image) server:

<img src="http://ImageServer/image.png"/>

All is fine when computer from Small network is loading the webpage from Main server as it has access to Image server too (the same network). Problem occurs when the computer from Large network loads the webpage. The image is not loading because Image server is in Small network which is not accessible for machines from Large LAN.
Is there any way to force Main server to serve the image directly?

1条回答
手持菜刀,她持情操
2楼-- · 2019-09-16 17:43

I don't know why I couldn't find this before posting my question. The simplest approach seems to be proper router configuration. But... changing router configuration is not possible in my situation. Knowing all that I started up my own brain finally ;). My solution is converting the image to base64 string first with the following C# snippet:

    private string convertToBase64(string imageURL)
    {
        var request = WebRequest.Create(imageURL);

        using (var response = request.GetResponse())
        {
            using (var stream = response.GetResponseStream())
            {
                using (Image image = Image.FromStream(stream))
                {
                    using (MemoryStream m = new MemoryStream())
                    {
                        image.Save(m, image.RawFormat);
                        byte[] imageBytes = m.ToArray();
                        string base64String = Convert.ToBase64String(imageBytes);
                        return string.Format("data:image/png;base64,{0}", base64String);
                    }
                }
            }
        }
    }

It's all happening at the server side so no issues with access to image.
Then I'm passing the string to the View via Model property and displaying the image as follows:

<img id="photo" src="@Model.Base64Image" title="@Model.Description" />

Probably this solution has it's flaws, but it works for me, and I couldn't find anything else that I could use in this case.

查看更多
登录 后发表回答