Loading image from remote server in different LAN

♀尐吖头ヾ 提交于 2019-12-12 05:26:56

问题


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:


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.



来源:https://stackoverflow.com/questions/37293184/loading-image-from-remote-server-in-different-lan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!