Меню

Not allowed to load local resource ошибка

Okay folks, I completely understand the security reasons behind this error message, but sometimes, we do need a workaround… and here’s mine. It uses ASP.Net (rather than JavaScript, which this question was based on) but it’ll hopefully be useful to someone.

Our in-house app has a webpage where users can create a list of shortcuts to useful files spread throughout our network. When they click on one of these shortcuts, we want to open these files… but of course, Chrome’s error prevents this.

enter image description here

This webpage uses AngularJS 1.x to list the various shortcuts.

Originally, my webpage was attempting to directly create an <a href..> element pointing at the files, but this produced the «Not allowed to load local resource» error when a user clicked on one of these links.

<div ng-repeat='sc in listOfShortcuts' id="{{sc.ShtCut_ID}}" class="cssOneShortcutRecord" >
    <div class="cssShortcutIcon">
        <img ng-src="{{ GetIconName(sc.ShtCut_PathFilename); }}">
    </div>
    <div class="cssShortcutName">
        <a ng-href="{{ sc.ShtCut_PathFilename }}" ng-attr-title="{{sc.ShtCut_Tooltip}}" target="_blank" >{{ sc.ShtCut_Name }}</a>
    </div>
</div>

The solution was to replace those <a href..> elements with this code, to call a function in my Angular controller…

<div ng-click="OpenAnExternalFile(sc.ShtCut_PathFilename);" >
    {{ sc.ShtCut_Name }}
</div>

The function itself is very simple…

$scope.OpenAnExternalFile = function (filename) {
    //
    //  Open an external file (i.e. a file which ISN'T in our IIS folder)
    //  To do this, we get an ASP.Net Handler to manually load the file, 
    //  then return it's contents in a Response.
    //
    var URL = '/Handlers/DownloadExternalFile.ashx?filename=' + encodeURIComponent(filename);
    window.open(URL);
}

And in my ASP.Net project, I added a Handler file called DownloadExternalFile.aspx which contained this code:

namespace MikesProject.Handlers
{
    /// <summary>
    /// Summary description for DownloadExternalFile
    /// </summary>
    public class DownloadExternalFile : IHttpHandler
    {
        //  We can't directly open a network file using Javascript, eg
        //      window.open("\SomeNetworkPathExcelFileMikesExcelFile.xls");
        //
        //  Instead, we need to get Javascript to call this groovy helper class which loads such a file, then sends it to the stream.  
        //      window.open("/Handlers/DownloadExternalFile.ashx?filename=//SomeNetworkPath/ExcelFile/MikesExcelFile.xls");
        //
        public void ProcessRequest(HttpContext context)
        {
            string pathAndFilename = context.Request["filename"];               //  eg  "\SomeNetworkPathExcelFileMikesExcelFile.xls"
            string filename = System.IO.Path.GetFileName(pathAndFilename);      //  eg  "MikesExcelFile.xls"

            context.Response.ClearContent();

            WebClient webClient = new WebClient();
            using (Stream stream = webClient.OpenRead(pathAndFilename))
            {
                // Process image...
                byte[] data1 = new byte[stream.Length];
                stream.Read(data1, 0, data1.Length);

                context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", filename));
                context.Response.BinaryWrite(data1);

                context.Response.Flush();
                context.Response.SuppressContent = true;
                context.ApplicationInstance.CompleteRequest();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

And that’s it.

Now, when a user clicks on one of my Shortcut links, it calls the OpenAnExternalFile function, which opens this .ashx file, passing it the path+filename of the file we want to open.

This Handler code loads the file, then passes it’s contents back in the HTTP response.

And, job done, the webpage opens the external file.

Phew ! Again — there is a reason why Chrome throws this «Not allowed to load local resources» exception, so tread carefully with this… but I’m posting this code just to demonstrate that this is a fairly simple way around this limitation.

Just one last comment: the original question wanted to open the file «C:02.jpg«. You can’t do this. Your website will sit on one server (with it’s own C: drive) and has no direct access to your user’s own C: drive. So the best you can do is use code like mine to access files somewhere on a network drive.

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

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 :

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

Js

Upload file & append result to a 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
                }
           });

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

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 :

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

Js

Upload file & append result to a 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
                }
           });

@Robbyn666 Still not getting it. This is my package.json
{ "name": "angular-electron", "version": "0.0.0", "main": "main.js", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e", "electron": "electron .", "electron-build": "ng build --prod && electron ." }, "private": true, "dependencies": { "@angular/animations": "^6.1.0", "@angular/common": "^6.1.0", "@angular/compiler": "^6.1.0", "@angular/core": "^6.1.0", "@angular/forms": "^6.1.0", "@angular/http": "^6.1.0", "@angular/platform-browser": "^6.1.0", "@angular/platform-browser-dynamic": "^6.1.0", "@angular/router": "^6.1.0", "core-js": "^2.5.4", "rxjs": "^6.0.0", "zone.js": "~0.8.26" }, "devDependencies": { "@angular-devkit/build-angular": "~0.7.0", "@angular/cli": "~6.1.2", "@angular/compiler-cli": "^6.1.0", "@angular/language-service": "^6.1.0", "@types/jasmine": "~2.8.6", "@types/jasminewd2": "~2.0.3", "@types/node": "~8.9.4", "codelyzer": "~4.2.1", "electron": "^2.0.6", "jasmine-core": "~2.99.1", "jasmine-spec-reporter": "~4.2.1", "karma": "~1.7.1", "karma-chrome-launcher": "~2.2.0", "karma-coverage-istanbul-reporter": "~2.0.0", "karma-jasmine": "~1.1.1", "karma-jasmine-html-reporter": "^0.2.2", "protractor": "~5.3.0", "ts-node": "~5.0.1", "tslint": "~5.9.1", "typescript": "~2.7.2" } }
In which object do i add "directories": { "output": "release/" } ??

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Not all arguments converted during string formatting python ошибка
  • Not accessible ошибка принтера