Javascript 无法打开本地文件 - Chrome:不允许加载本地资源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39007243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:06:59  来源:igfitidea点击:

Cannot open local file - Chrome: Not allowed to load local resource

javascriptjquerygoogle-chromewebwindow.open

提问by KBH

Test browser: Version of Chrome: 52.0.2743.116

测试浏览器:Chrome 版本:52.0.2743.116

It is a simple javascript that is to open an image file from local like 'C:\002.jpg'

这是一个简单的 javascript,用于从本地打开图像文件,如 'C:\002.jpg'

function run(){

   var URL = "file:///C:
<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>
2.jpg"; window.open(URL, null); } run();

Here is my sample code. https://fiddle.jshell.net/q326vLya/3/

这是我的示例代码。 https://fiddle.jshell.net/q326vLya/3/

Please give me any suitable suggestions.

请给我任何合适的建议。

采纳答案by Woody

Know this is kind of old, but see many questions like this...

知道这有点旧,但看到很多这样的问题......

We use Chrome a lot in the classroom and it is a must to working with local files.

我们在课堂上经常使用 Chrome,因此必须使用本地文件。

What we have been using is "Web Server for Chrome". You start it up, choose the folder wishing to work with and go to URL (like 127.0.0.1:port you chose)

我们一直在使用的是“Web Server for Chrome”。您启动它,选择希望使用的文件夹并转到 URL(例如您选择的 127.0.0.1:port)

It is a simple server and cannot use PHP but for simple work, might be your solution:

它是一个简单的服务器,不能使用 PHP,但对于简单的工作,可能是您的解决方案:

https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb

https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb

回答by Mike Gledhill

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.

好的,伙计们,我完全理解此错误消息背后的安全原因,但有时,我们确实需要一种解决方法......这是我的。它使用 ASP.Net(而不是这个问题所基于的 JavaScript),但它希望对某人有用。

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.

我们的内部应用程序有一个网页,用户可以在其中创建一个快捷方式列表,这些文件指向遍布我们网络的有用文件。当他们点击这些快捷方式之一时,我们想要打开这些文件……但当然,Chrome 的错误阻止了这一点。

enter image description here

在此处输入图片说明

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

本网页使用 AngularJS 1.x 来列出各种快捷方式。

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.

最初,我的网页试图直接创建一个<a href..>指向文件的元素,但是Not allowed to load local resource当用户单击这些链接之一时,这会产生“ ”错误。

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

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

解决方案是<a href..>用这段代码替换这些元素,在我的 Angular 控制器中调用一个函数......

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

The function itself is very simple...

功能本身很简单...

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("\SomeNetworkPath\ExcelFile\MikesExcelFile.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  "\SomeNetworkPath\ExcelFile\MikesExcelFile.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 in my ASP.Net project, I added a Handler file called DownloadExternalFile.aspxwhich contained this code:

在我的 ASP.Net 项目中,我添加了一个名为的 Handler 文件DownloadExternalFile.aspx,其中包含以下代码:

function run(){
   // 8887 is the port number you have launched your serve
   var URL = "http://127.0.0.1:8887/002.jpg";

   window.open(URL, null);

}
run();

And that's it.

就是这样。

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

现在,当用户单击我的快捷方式链接之一时,它会调用OpenAnExternalFile打开此 .ashx 文件的函数,并将我们要打开的文件的路径+文件名传递给它。

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

此处理程序代码加载文件,然后在 HTTP 响应中将其内容传回。

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.

呼!再次 - Chrome 抛出这个“ Not allowed to load local resources”异常是有原因的,所以要小心处理这个......但我发布这段代码只是为了证明这是绕过这个限制的一种相当简单的方法。

Just one last comment: the original question wanted to open the file "C:\002.jpg". You can'tdo 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.

只有最后一个评论:原来的问题想打开文件“ C:\002.jpg”。你不能这样做。您的网站将位于一台服务器上(使用它自己的 C: 驱动器)并且无法直接访问您用户自己的 C: 驱动器。所以你能做的最好的事情就是使用像我这样的代码来访问网络驱动器上某处的文件。

回答by Scott

Chrome specifically blocks local file access this way for security reasons.

出于安全原因,Chrome 专门以这种方式阻止本地文件访问。

Here's a workaround to enable the flag in Chrome (and open your system up to vulnerabilities):

这是在 Chrome 中启用该标志的解决方法(并使您的系统暴露于漏洞):

c:\Program Files (x86)\google\chrome\Application\chrome.exe --allow-file-access-from-files

c:\Program Files (x86)\google\chrome\Application\chrome.exe --allow-file-access-from-files

回答by Alex

1) Open your terminal and type

1)打开你的终端并输入

npm install -g http-server

npm install -g http-server

2) Go to the root folder that you want to serve you files and type:

2)转到您要为您提供文件的根文件夹并键入:

http-server ./

http-server ./

3) Read the output of the terminal, something kinda http://localhost:8080will appear.

3)阅读终端的输出,http://localhost:8080会出现一些东西。

Everything on there will be allowed to be got. Example:

那里的一切都将被允许获得。例子:

background: url('http://localhost:8080/waw.png');

background: url('http://localhost:8080/waw.png');

回答by Shwetabh Shekhar

There is a workaround using Web Server for Chrome.
Here are the steps:

有一个使用Web Server for Chrome的解决方法。
以下是步骤:

  1. Add the Extension to chrome.
  2. Choose the folder (C:\images)and launch the server on your desired port.
  1. 将扩展添加到 chrome。
  2. 选择文件夹(C:\images)并在所需端口上启动服务器。

Now easily access your local file:

现在轻松访问您的本地文件:

<img src="/Content/my-image.jpg" />

PS: You might need to select the CORS Header option from advanced setting incase you face any error any cross origin access error.

PS:您可能需要从高级设置中选择 CORS Header 选项,以防您遇到任何错误,任何跨源访问错误。

回答by PontiusTheBarbarian

You won't be able to load an image outside of the project directory or from a user level directory, hence the "cannot access local resource warning".

您将无法在项目目录之外或从用户级目录加载图像,因此“无法访问本地资源警告”。

But if you were to place the file in a root folder of your project like in {rootFolder}\Content\my-image.jpgand referenced it like so:

但是,如果您要将文件放在项目的根文件夹中,例如 in{rootFolder}\Content\my-image.jpg并像这样引用它:

$path = 'E:/pat/rwanda.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

回答by Ruberandinda Patience

This issue come when I am using PHP as server side language and the work around was to generate base64 enconding of my image before sending the result to client

当我使用 PHP 作为服务器端语言并且解决方法是在将结果发送到客户端之前生成我的图像的 base64 编码时会出现这个问题

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;

I think may give someone idea to create his own work around

我认为可能会给某人创造自己的工作的想法

Thanks

谢谢

回答by Prak

If you could do this, it will represent a big security problem, as you can access your filesystem, and potentially act on the data available there... Luckily it's not possible to do what you're trying to do.

如果你能做到这一点,这将代表一个很大的安全问题,因为你可以访问你的文件系统,并可能对那里的可用数据采取行动......幸运的是,你不可能做你想做的事情。

If you need local resources to be accessed, you can try to start a web server on your machine, and in this case your method will work. Other workarounds are possible, such as acting on Chrome settings, but I always prefer the clean way, installing a local web server, maybe on a different port (no, it's not so difficult!).

如果您需要访问本地资源,您可以尝试在您的机器上启动一个 Web 服务器,在这种情况下,您的方法将起作用。其他解决方法也是可能的,例如对 Chrome 设置进行操作,但我总是更喜欢干净的方式,安装本地 Web 服务器,也许在不同的端口上(不,这并不难!)。

See also:

也可以看看:

回答by Maishidh Mandviwala

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

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

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.

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

function run(){
var URL = "http://172.271.1.20:8000/" /* http://0.0.0.0:8000/ or http://127.0.0.1:8000/; */
window.open(URL, null);
}

回答by shah

Google Chrome does not allow to load local resources because of the security. Chrome need http url. Internet Explorer and Edge allows to load local resources, but Safari, Chrome, and Firefox doesn't allows to load local resources.

出于安全考虑,谷歌浏览器不允许加载本地资源。Chrome 需要 http 网址。Internet Explorer 和 Edge 允许加载本地资源,但 Safari、Chrome 和 Firefox 不允许加载本地资源。

Go to file location and start the Python Server from there.

转到文件位置并从那里启动 Python 服务器。

python -m SimpleHttpServer

python -m SimpleHttpServer

then put that url into function:

然后将该网址放入函数中:

##代码##