简体   繁体   English

不允许加载本地资源错误

[英]Not allowed to load local resource Error

I want to show the uploaded image after uploading it but I can not. 我想在上传后显示上传的图像,但是不能。 I get an error from my JS console saying: Not allowed to load local resource Error 我从JS控制台收到一条错误消息: Not allowed to load local resource Error

Here is my code : 这是我的代码:

Controller Method : 控制器方式:

get file and save it to localsystem 获取文件并将其保存到本地系统

[HttpPost]
// public static readonly string TEMPORARY_FILES_UPLOADS_PATH = "~/Uploads/Tmp";     
public ActionResult UploadFileToTemporaryFolder(HttpPostedFileBase file)
            {
                string fileName = String.Empty;
                string path = String.Empty;
                if (file != null)
                {
                    try
                    {
                       string timestamp = DateTime.UtcNow.ToString("yyyy_MM_dd_HH_mm_ss_fff",CultureInfo.InvariantCulture);
                       fileName = timestamp + "_" + Path.GetFileName(file.FileName);
                       path = string.Format("{0}/{1}", Server.MapPath(ApplicationConfig.TEMPORARY_FILES_UPLOADS_PATH), fileName);
                        System.IO.Directory.CreateDirectory(Server.MapPath(ApplicationConfig.TEMPORARY_FILES_UPLOADS_PATH));
                        file.SaveAs(path);
                    }
                    catch (Exception)
                    {}
                }
                return Json(new { FileName = fileName, FilePath=path }, JsonRequestBehavior.AllowGet);
            }

HTML : HTML:

<input id="HotelJustificatifFile" type="file" value="joindre pièce" name="upload"  >
<div id="JustificatifsHotelSection" style="display:block;"></div>

Js JS

Upload file & append result to a div 上传文件并将结果附加到div

 $('body').on('change', '#HotelJustificatifFile', function () {

               var file = document.getElementById('HotelJustificatifFile').files[0];
               if (file != null) {
                   var myData = new FormData();
                   myData.append("file", file);

                   // Uploading File via Ajax To Temporar Folder
                   $.ajax({
                       type: "POST",
                       url: "<%: Url.Action("UploadFileToTemporaryFolder","Enqueteur") %>",
                       processData: false,
                       contentType: false,
                       data: myData,
                       cache: false,
                       dataType: "json",
                       success: function (result) {
                           if (result.FileName != '') {

                               var fileName = result.FileName;
                               var filePath = result.FilePath;

                               //alert(filePath );
                               var imageDiv = "<div>";
                               imageDiv+='<div style="z-index: 10; position: absolute; top: 4px; left: 10px;">';
                               imageDiv += '<a onclick="afficherImage(' + fileName + ')" >Supprimer</a>';
                               imageDiv +='</div>';
                               imageDiv += '<img u=image src="' +filePath + '" />';
                               imageDiv += '</div>';
                               // Adding Image To the Div 
                               $('#JustificatifsHotelSection').append(imageDiv);

                           }
                           },
                       failure: function () {
                       }
                   });

                   // Else
                }
           });

you can not return the physical file path 您无法返回物理文件路径

Tries to return the image url (http: //...../imageName) 尝试返回图像网址(http://...../imageName)

Or you can use html5 API to show images in the browser without having to upload the image to the server: 或者,您可以使用html5 API在浏览器中显示图像,而不必将图像上传到服务器:

var file = document.getElementById(HotelJustificatifFile).files[0];
var reader = new FileReader();
var img = new Image();
img.src = reader.result;
youDivContainerForImage.appendChild(img);

不允许加载本地资源错误,可能是此链接可以解决您的问题.. http://www.scriptscoop.net/t/17cccd1064d6/angularjs-1-2-not-allowed-to-load-local-resource.html

You are returning physical file path consider this instead: 您要返回物理文件路径,请考虑以下内容:

var virtualPath=Url.Content(string.Format("{0}/{1}",
    ApplicationConfig.TEMPORARY_FILES_UPLOADS_PATH, fileName));

return Json(new { FileName = fileName, FilePath=virtualPath}, 
    JsonRequestBehavior.AllowGet);

I'd like to point out that Javascript can do this on its own, without sending the file through an API at all. 我想指出的是,Javascript可以自己执行此操作,而根本不需要通过API发送文件。

Web pages aren't allowed to dork around with files on the user's computer (physical file paths beginning with file:/// ), and I'm glad they aren't. 网页不允许与用户计算机上的文件(以file:///开头的物理文件路径) file:/// ,我很高兴他们没有这样做。 Do you want random people on the Internet playing with stuff on your computer? 您是否希望互联网上的随机人在玩计算机上的东西? Of course you don't. 当然不会。

Luckily, you can access any file the user chooses to upload (via a file input) using a data url (these begin with data:[MIME type];base64, ), and you can get one via Javascript's built-in FileReader object. 幸运的是,您可以使用数据url(以data:[MIME type];base64,开头)访问用户选择通过文件输入上传的任何文件,并且可以通过Javascript的内置FileReader对象获得一个。 See below: 见下文:

var previewImage = document.getElementById('my-preview');

var filereader = new FileReader();
filereader.onload = function (event) {
  var data = event.target.result;

  previewImage.src = data;
};

var file = document.getElementById('file-input').files[0];
filereader.readAsDataUrl(file);

Basically, this uses the FileReader to turn the user's uploaded file into a base64 data: URL, which you are free to use however you want (and the <img> tag isn't afraid to use it as a src attribute). 基本上,这使用FileReader将用户上传的文件转换为base64 data: URL,您可以随意使用它(并且<img>标签不怕将其用作src属性)。

That's a win. 那是胜利。 You've got your preview image and you didn't have to get around sensible browser security to do it. 您已经获得了预览图像,而不必绕开明智的浏览器安全性来进行操作。

i resolved the probleme , here is my controller method : 我解决了问题,这是我的控制器方法:

    [HttpPost]
            public ActionResult UploadFileToTemporaryFolder(HttpPostedFileBase file)
            {
                string fileName = String.Empty;
                string path = String.Empty;
                if (file != null)
                {
                    try
                    {
                       string timestamp = DateTime.UtcNow.ToString("yyyy_MM_dd_HH_mm_ss_fff",CultureInfo.InvariantCulture);
                       fileName = timestamp + "_" + Path.GetFileName(file.FileName);
                      // Relative Path ex "/uploads/Tmp"
                       path = Url.Content(ApplicationConfig.TEMPORARY_FILES_UPLOADS_PATH);
                       System.IO.Directory.CreateDirectory(Server.MapPath(ApplicationConfig.TEMPORARY_FILES_UPLOADS_PATH));
                       // absolute path : C://........../uploads/Tmp
                       string fileSystemPath = string.Format("{0}/{1}", Server.MapPath(ApplicationConfig.TEMPORARY_FILES_UPLOADS_PATH), fileName);
                       file.SaveAs(fileSystemPath);
                    }
                    catch (Exception)
                    {}
                }
               // i send the relative path + filename
                return Json(new { FileName = fileName, FilePath=path }, JsonRequestBehavior.AllowGet);
            }

And I get The Path in my Js Code like that : 我在我的Js代码中得到的路径是:

success: function (result) {
                           if (result.FileName != '') {

                               var fileName = result.FileName;
                               var filePath = result.FilePath;

                               //alert(filePath );
                                var imageDiv = '<div>';
                                imageDiv+='<div style="z-index: 10; position: absolute; top: 4px; left: 10px;">';
                                        imageDiv += '<a onclick="afficherImage(' + fileName + ')" >Supprimer</a>';
                                     imageDiv +='</div>';
                                     imageDiv += '<img style="width:100%; height:500px" u=image src="' +filePath +'/'+fileName+ '" />';
                                   imageDiv += '</div>';
                               // Adding Image To the Div 
                                   $('#HotelJustifS').append(imageDiv);

                           }
                           }

You just need to replace all image network paths(or local path) with byte strings in stored Encoded HTML sting. 您只需要用存储的已编码HTML字符串中的字节字符串替换所有图像网络路径(或本地路径)即可。 For this you required HtmlAgilityPack to convert Html string to Html document. 为此,您需要HtmlAgilityPack将HTML字符串转换为HTML文档。 https://www.nuget.org/packages/HtmlAgilityPack https://www.nuget.org/packages/HtmlAgilityPack

Find Below code to convert each image src network path(or local path) to byte sting. 查找以下代码将每个图像src网络路径(或本地路径)转换为字节字符串。 It will definitely display all images with network path(or local path) in IE,chrome and firefox. 它肯定会在IE,chrome和firefox中显示具有网络路径(或本地路径)的所有图像。

string encodedHtmlString = Emailmodel.DtEmailFields.Rows[0]["Body"].ToString(); 字符串编码的HtmlString = 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM