不允许加载本地资源错误

本文关键字:资源 错误 加载 不允许 | 更新日期: 2023-09-27 18:16:26

我想在上传后显示上传的图像,但我不能。我得到一个错误从我的JS控制台说:Not allowed to load local resource Error

下面是我的代码:

控制器方法:

获取文件并保存到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:

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

Js

上传文件&将结果追加到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
                }
           });

不允许加载本地资源错误

不能返回物理文件路径

尝试返回图像url (http://...../imageName)

或者您可以使用html5 API在浏览器中显示图像,而无需将图像上传到服务器:

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

您返回的是物理文件路径,请考虑这样做:

var virtualPath=Url.Content(string.Format("{0}/{1}",
    ApplicationConfig.TEMPORARY_FILES_UPLOADS_PATH, fileName));
return Json(new { FileName = fileName, FilePath=virtualPath}, 
    JsonRequestBehavior.AllowGet);

不允许加载本地资源错误,可能是这个链接解决了你的答案。http://www.scriptscoop.net/t/17cccd1064d6/angularjs-1-2-not-allowed-to-load-local-resource.html

我想指出的是,Javascript可以自己做到这一点,而不需要通过API发送文件。

网页不允许篡改用户计算机上的文件(以file:///开头的物理文件路径),我很高兴它们不允许这样做。你想让网上随便的人玩你电脑上的东西吗?你当然不知道。

幸运的是,您可以使用数据url(以data:[MIME type];base64,开头)访问用户选择上传的任何文件(通过文件输入),并且您可以通过Javascript的内置FileReader对象获得一个。见下文:

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);

基本上,这使用FileReader将用户上传的文件转换为base64 data: URL,您可以随意使用该URL(并且<img>标记不怕将其用作src属性)。

那是一个胜利。你已经有了你的预览图像,你不需要绕过明智的浏览器安全来做。

我解决了这个问题,这里是我的控制器方法:

    [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);
            }

我在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);
                           }
                           }

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

找到下面的代码将每个图像src网络路径(或本地路径)转换为字节串。在IE,chrome和firefox中,它绝对会显示所有带有网络路径(或本地路径)的图像。

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;