且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

不允许加载本地资源:

更新时间:2022-11-16 23:08:20

您只需要将所有图像/视频网络路径(或本地路径)替换为存储的已编码HTML字符串中的字节字符串即可. 为此,您需要HtmlAgilityPack将HTML字符串转换为HTML文档. https://www.nuget.org/packages/HtmlAgilityPack

You just need to replace all image/video network paths(or local path) to byte strings in stored Encoded HTML sting. For this you required HtmlAgilityPack to convert Html string to Html document. https://www.nuget.org/packages/HtmlAgilityPack

查找以下代码,将每个图像src网络路径(或本地路径)转换为字节字符串. 它肯定会在IE,chrome和firefox中显示所有具有网络路径(或本地路径)的图像.

Find Below code to convert each image src network path(or local path) to byte sting. It will definitely display all images with network path(or local path) in IE,chrome and firefox.

string encodingHtmlString = Emailmodel.DtEmailFields.Rows [0] ["Body"].ToString();

string encodedHtmlString = Emailmodel.DtEmailFields.Rows[0]["Body"].ToString();

            // Decode the encoded string.
            StringWriter myWriter = new StringWriter();
            HttpUtility.HtmlDecode(encodedHtmlString, myWriter);
            string DecodedHtmlString = myWriter.ToString();

            //find and replace each img src with byte string
             HtmlDocument document = new HtmlDocument();
             document.LoadHtml(DecodedHtmlString);
             document.DocumentNode.Descendants("img")
              .Where(e =>
            {
                string src = e.GetAttributeValue("src", null) ?? "";
                return !string.IsNullOrEmpty(src);//&& src.StartsWith("data:image");
            })
            .ToList()
                        .ForEach(x =>
                        {
                            string currentSrcValue = x.GetAttributeValue("src", null);                                
                            string filePath = Path.GetDirectoryName(currentSrcValue) + "\\";
                            string filename = Path.GetFileName(currentSrcValue);
                            string contenttype = "image/" + Path.GetExtension(filename).Replace(".", "");
                            FileStream fs = new FileStream(filePath + filename, FileMode.Open, FileAccess.Read);
                            BinaryReader br = new BinaryReader(fs);
                            Byte[] bytes = br.ReadBytes((Int32)fs.Length);
                            br.Close();
                            fs.Close();
                            x.SetAttributeValue("src", "data:" + contenttype + ";base64," + Convert.ToBase64String(bytes));                                
                        });

            string result = document.DocumentNode.OuterHtml;
            //Encode HTML string
            string myEncodedString = HttpUtility.HtmlEncode(result);

            Emailmodel.DtEmailFields.Rows[0]["Body"] = myEncodedString;