Html Internet 浏览器中的文件 URL“不允许加载本地资源”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34901523/
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
File URL "Not allowed to load local resource" in the Internet Browser
提问by Benny Niemeijer
I've got a major brainteaser.
我有一个重要的脑筋急转弯。
I want to open a file in classic ASP. I'm using various variables because things can change but the outcome is correct. I know this because I've tested the outcome by copying the linkadress and placing it in my URL. Now the problem: If I click my link it doesn't do anything. Not a refresh, not a redirect. nothing. Does anyone know what I did wrong?
我想在经典的 ASP 中打开一个文件。我使用了各种变量,因为事情可能会改变,但结果是正确的。我知道这一点,因为我已经通过复制链接地址并将其放在我的 URL 中来测试结果。现在的问题是:如果我点击我的链接,它不会做任何事情。不是刷新,也不是重定向。没有。有谁知道我做错了什么?
Ok here's the deal. My file isn't always local, it depends on what environment I'm on. If I copy-paste the outcome of my url it does download. If I click my URL it doesn't respond. Any ideas? Browser problem? (although I've tested 5 browsers) Or anything else? I'm really stuck here and the internet does not seem to be on my side.
好的,这是交易。我的文件并不总是本地的,这取决于我所在的环境。如果我复制粘贴我的 url 的结果,它会下载。如果我单击我的 URL,它不会响应。有任何想法吗?浏览器问题?(虽然我已经测试了 5 个浏览器)或者其他什么?我真的被困在这里,互联网似乎并不站在我这边。
I've got 3 environments. The variables underneath here are so that the link works. I know the link works because I've tested it by copying. And yes, it does begin with file:///
and yes I'm sure the link is right.
我有3个环境。下面的变量是为了使链接有效。我知道该链接有效,因为我已经通过复制对其进行了测试。是的,它确实以开头,file:///
是的,我确定链接是正确的。
Here's my line of code:
这是我的代码行:
response.write("<td class='tab_kolom2'><a href='"&rootRs("pre_rootpad")&rootRs("rootpad_protocollen")&"\"&overzichtRs("Formuliernr")&"\Uitvoeringsoverzicht.xls' target='_blank' download>Click here</a></td>")
EDIT: Screenshot with error/outcome of link
编辑:链接错误/结果的截图
采纳答案by Lankymart
Now we know what the actual error is can formulate an answer.
现在我们知道实际的错误是什么可以制定一个答案。
Not allowed to load local resource
不允许加载本地资源
is a Security exception built into Chrome and other modern browsers. The wording may be different but in some way shape or form they all have security exceptions in place to deal with this scenario.
是 Chrome 和其他现代浏览器中内置的安全例外。措辞可能不同,但在某种形式或形式上,它们都有处理这种情况的安全例外。
In the past you could override certain settings or apply certain flags such as
过去,您可以覆盖某些设置或应用某些标志,例如
--disable-web-security --allow-file-access-from-files --allow-file-access
in Chrome (See https://stackoverflow.com/a/22027002/692942)
在 Chrome 中(见https://stackoverflow.com/a/22027002/692942)
It's there for a reason
At this point though it's worth pointing out that these security exceptions exist for good reason and trying to circumvent them isn't the best idea.
这是有原因的
在这一点上,尽管值得指出,这些安全例外的存在是有充分理由的,试图规避它们并不是最好的主意。
There is another way
还有另一种方式
As you have access to Classic ASP already you could always build a intermediary page that serves the network based files. You do this using a combination of the ADODB.Stream
object and the Response.BinaryWrite()
method. Doing this ensures your network file locations are never exposed to the client and due to the flexibility of the script it can be used to load resources from multiple locations and multiple file types.
由于您已经可以访问 Classic ASP,因此您始终可以构建一个为基于网络的文件提供服务的中间页面。您可以使用ADODB.Stream
对象和Response.BinaryWrite()
方法的组合来执行此操作。这样做可确保您的网络文件位置永远不会暴露给客户端,并且由于脚本的灵活性,它可用于从多个位置和多种文件类型加载资源。
Here is a basic example (getfile.asp
);
这是一个基本的例子( getfile.asp
);
<%
Option Explicit
Dim s, id, bin, file, filename, mime
id = Request.QueryString("id")
'id can be anything just use it as a key to identify the
'file to return. It could be a simple Case statement like this
'or even pulled from a database.
Select Case id
Case "TESTFILE1"
'The file, mime and filename can be built-up anyway they don't
'have to be hard coded.
file = "\server\share\Projecten\Protocollen6\Uitvoeringsoverzicht.xls"
mime = "application/vnd.ms-excel"
'Filename you want to display when downloading the resource.
filename = "Uitvoeringsoverzicht.xls"
'Assuming other files
Case ...
End Select
If Len(file & "") > 0 Then
Set s = Server.CreateObject("ADODB.Stream")
s.Type = adTypeBinary 'adTypeBinary = 1 See "Useful Links"
Call s.Open()
Call s.LoadFromFile(file)
bin = s.Read()
'Clean-up the stream and free memory
Call s.Close()
Set s = Nothing
'Set content type header based on mime variable
Response.ContentType = mime
'Control how the content is returned using the
'Content-Disposition HTTP Header. Using "attachment" forces the resource
'to prompt the client to download while "inline" allows the resource to
'download and display in the client (useful for returning images
'as the "src" of a <img> tag).
Call Response.AddHeader("Content-Disposition", "attachment;filename=" & filename)
Call Response.BinaryWrite(bin)
Else
'Return a 404 if there's no file.
Response.Status = "404 Not Found"
End If
%>
This example is pseudo coded and as such is untested.
这个例子是伪编码的,因此未经测试。
This script can then be used in <a>
like this to return the resource;
然后可以<a>
像这样使用此脚本来返回资源;
<a href="/getfile.asp?id=TESTFILE1">Click Here</a>
The could take this approach further and consider (especially for larger files)reading the file in chunks using Response.IsConnected
to check whether the client is still there and s.EOS
property to check for the end of the stream while the chunks are being read. You could also add to the querystring parameters to set whether you want the file to return in-line or prompt to be downloaded.
可以进一步采用这种方法并考虑(尤其是对于较大的文件)以块的形式读取文件,Response.IsConnected
用于检查客户端是否仍然存在,并s.EOS
在读取块时检查流的结尾。您还可以添加到查询字符串参数以设置是希望文件内嵌返回还是提示下载。
Useful Links
有用的链接
Using
METADATA
to Import DLL Constants- If you are having trouble gettingadTypeBinary
to be recongnised, always better then just hard coding1
.Content-Disposition:What are the differences between “inline” and “attachment”?- Useful information about how
Content-Disposition
behaves on the client.
使用
METADATA
导入DLL常量-如果你有麻烦adTypeBinary
要计入初始确认,总是更好然后就硬编码1
。Content-Disposition:“内联”和“附件”有什么区别?- 有关
Content-Disposition
客户端行为的有用信息。
回答by alix
For people do not like to modify chrome's security options, we can simply start a python
http server from directory which contains your local file:
对于不喜欢修改 chrome 安全选项的人,我们可以简单地python
从包含本地文件的目录启动一个http 服务器:
python -m SimpleHTTPServer
and for python 3:
对于python 3:
python3 -m http.server
Now you can reach any local file directly from your js code or externally with http://127.0.0.1:8000/some_file.txt
现在您可以直接从您的 js 代码或外部使用http://127.0.0.1:8000/some_file.txt访问任何本地文件
回答by gpinkas
You will have to provide a link to your file that is accessible through the browser, that is for instance:
您必须提供可通过浏览器访问的文件链接,例如:
<a href="http://my.domain.com/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">
versus
相对
<a href="C:/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">
If you expose your "Projecten" folder directly to the public, then you may only have to provide the link as such:
如果您直接向公众公开您的“Projecten”文件夹,那么您可能只需要提供如下链接:
<a href="/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">
But beware, that your files can then be indexed by search engines, can be accessed by anybody having this link, etc.
但请注意,您的文件可能会被搜索引擎索引,任何拥有此链接的人都可以访问,等等。
回答by Rich
I didn't realise from your original question that you were opening a file on the local machine, I thought you were sending a file from the web server to the client.
我没有从你最初的问题中意识到你是在本地机器上打开一个文件,我以为你是从 web 服务器向客户端发送一个文件。
Based on your screenshot, try formatting your link like so:
根据您的屏幕截图,尝试像这样格式化您的链接:
<a href="file:///C:/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">Klik hier</a>
(without knowing the contents of each of your recordset variables I can't give you the exact ASP code)
(在不知道每个记录集变量的内容的情况下,我无法为您提供确切的 ASP 代码)
回答by Maishidh Mandviwala
You just need to replace all image network paths to byte strings in HTML string. For this first 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 中显示所有带有网络路径(或本地路径)的图像。
string encodedHtmlString = Emailmodel.DtEmailFields.Rows[0]["Body"].ToString();
string encodingHtmlString = 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;