好的,伙计们,我完全理解此错误消息背后的安全原因,但有时,我们确实需要一种解决方法......这是我的。它使用 ASP.Net(而不是这个问题所基于的 JavaScript),但它希望对某人有用。
我们的内部应用程序有一个网页,用户可以在其中创建一个快捷方式列表,指向遍布我们网络的有用文件。当他们点击这些快捷方式之一时,我们想要打开这些文件……但当然,Chrome 的错误会阻止这一点。
此网页使用 AngularJS 1.x 列出各种快捷方式。
最初,我的网页试图直接创建一个指向文件的<a href..> 元素,但是当用户单击其中一个链接时,这会产生“Not allowed to load local resource”错误。
<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>
解决方案是用这段代码替换那些 <a href..> 元素,在我的 Angular 控制器中调用一个函数...
<div ng-click="OpenAnExternalFile(sc.ShtCut_PathFilename);" >
{{ sc.ShtCut_Name }}
</div>
函数本身很简单……
$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);
}
在我的 ASP.Net 项目中,我添加了一个名为 DownloadExternalFile.aspx 的处理程序文件,其中包含以下代码:
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;
}
}
}
就是这样。
现在,当用户单击我的一个快捷方式链接时,它会调用 OpenAnExternalFile 函数,该函数会打开这个 .ashx 文件,并将我们要打开的文件的路径+文件名传递给它。
此处理程序代码加载文件,然后将其内容传回 HTTP 响应中。
并且,工作完成,网页打开外部文件。
呸!再说一次 - Chrome 抛出这个“Not allowed to load local resources”异常是有原因的,所以要小心处理......但我发布这段代码只是为了证明这是一种解决这个限制的相当简单的方法。
最后一条评论:最初的问题是要打开文件“C:\002.jpg”。你不能这样做。您的网站将位于一台服务器上(具有自己的 C: 驱动器),并且无法直接访问用户自己的 C: 驱动器。所以你能做的最好的就是使用像我这样的代码来访问网络驱动器上某处的文件。