好夥計,我完全理解這背後的錯誤信息安全方面的原因,但有些時候,我們確實需要解決方法......而這是我的。它使用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..>
元素,調用一個函數在我的角度控制器...
<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。網項目,我添加了包含此代碼調用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:驅動器。所以你可以做的最好的就是使用我的代碼來訪問網絡驅動器上某處的文件。
使用''來獲取本地資源 – dandavis