로컬 파일을 열 수 없음-Chrome : 로컬 리소스를로드 할 수 없습니다.
테스트 브라우저 : Chrome 버전 : 52.0.2743.116
'C : \ 002.jpg'와 같은 로컬에서 이미지 파일을 여는 간단한 자바 스크립트입니다.
function run(){
var URL = "file:///C:\002.jpg";
window.open(URL, null);
}
run();
다음은 내 샘플 코드입니다. https://fiddle.jshell.net/q326vLya/3/
적절한 제안을 해주세요.
이것이 오래된 것임을 알고 있지만 이와 같은 많은 질문을보십시오 ...
우리는 교실에서 Chrome을 많이 사용하며 로컬 파일 작업에 필수입니다.
우리가 사용하고있는 것은 "Web Server for Chrome"입니다. 시작하고 작업 할 폴더를 선택하고 URL (예 : 선택한 127.0.0.1:port)로 이동합니다.
간단한 서버이며 PHP를 사용할 수 없지만 간단한 작업을 위해서는 솔루션이 될 수 있습니다.
https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb
좋아요 여러분, 저는이 오류 메시지의 보안 이유를 완전히 이해하고 있지만 때로는 해결 방법이 필요합니다. 여기에 제 것이 있습니다. 이 질문의 기반이 된 JavaScript 대신 ASP.Net을 사용하지만 누군가에게 유용하기를 바랍니다.
사내 앱에는 사용자가 네트워크 전체에 퍼져있는 유용한 파일에 대한 바로 가기 목록을 만들 수있는 웹 페이지가 있습니다. 이 바로 가기 중 하나를 클릭하면이 파일을 열고 싶지만 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
다음 코드가 포함 된 Handler 파일을 추가했습니다 .
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 응답에 해당 내용을 다시 전달합니다.
그리고 작업이 완료되면 웹 페이지에서 외부 파일을 엽니 다.
휴! 다시 말하지만, 크롬이이 " Not allowed to load local resources
"예외를 던지는 이유가 있습니다. 따라서 이것에 주의를 기울이십시오 ...하지만이 코드가이 제한을 우회하는 매우 간단한 방법임을 보여주기 위해이 코드를 게시하고 있습니다.
마지막 코멘트 : 원래 질문은 파일 " C:\002.jpg
"을 ( 를) 열고 싶었습니다 . 당신 은 이것을 할 수 없습니다 . 웹 사이트는 하나의 서버 (자체 C : 드라이브 포함)에 위치하며 사용자의 C : 드라이브에 직접 액세스 할 수 없습니다. 따라서 최선의 방법은 네트워크 드라이브의 어딘가에있는 파일에 액세스하기 위해 내 것과 같은 코드를 사용하는 것입니다.
Chrome은 특히 보안상의 이유로 이러한 방식으로 로컬 파일 액세스를 차단합니다.
다음은 Chrome에서 플래그를 해결하고 시스템을 취약하게 여는 문서입니다.
http://www.chrome-allow-file-access-from-file.com/
Chrome 용 웹 서버를 사용하는 해결 방법이 있습니다 .
단계는 다음과 같습니다.
- 크롬에 확장을 추가합니다.
- 폴더 (C : \ images)를 선택하고 원하는 포트에서 서버를 시작합니다.
이제 로컬 파일에 쉽게 액세스 할 수 있습니다.
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();
추신 : 원본 간 액세스 오류가 발생할 경우 고급 설정에서 CORS 헤더 옵션을 선택해야 할 수 있습니다.
1) 터미널을 열고 입력하십시오
npm install -g http-server
2) 파일을 제공하려는 루트 폴더로 이동하여 다음을 입력하십시오.
http-server ./
3) 터미널의 출력을 읽으면 뭔가 http://localhost:8080
가 나타납니다.
거기에있는 모든 것을 얻을 수 있습니다. 예:
background: url('http://localhost:8080/waw.png')
;
프로젝트 디렉터리 외부 또는 사용자 수준 디렉터리에서 이미지를로드 할 수 없으므로 "로컬 리소스에 액세스 할 수 없음 경고"가 표시됩니다.
그러나에서 {rootFolder}\Content\my-image.jpg
와 같이 프로젝트의 루트 폴더에 파일을 배치하고 다음과 같이 참조하는 경우 :
<img src="/Content/my-image.jpg" />
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!).
See also:
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
$path = 'E:/pat/rwanda.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
I think may give someone idea to create his own work around
Thanks
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
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.
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;
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.
Go to file location and start the Python Server from there.
python -m SimpleHttpServer
then put that url into function:
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);
}
This solution worked for me in PHP. It opens the PDF in the browser.
// $path is the path to the pdf file
public function showPDF($path) {
if($path) {
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=filename.pdf");
@readfile($path);
}
}
'Development Tip' 카테고리의 다른 글
여러 작업을위한 동일한 작업 공간 (0) | 2020.11.08 |
---|---|
Python "from [dot] package import…"구문 (0) | 2020.11.08 |
Java 클래스 이름의 유효한 문자 (0) | 2020.11.08 |
토렌트에서 DHT는 어떻게 작동합니까? (0) | 2020.11.08 |
std :: map 키 클래스가 유효한 키가 되려면 어떤 요구 사항을 충족해야합니까? (0) | 2020.11.08 |