2013-04-29 4 views
0

html 파일과 동일한 디렉토리에 저장된 파일을 읽을 수 있기를 원합니다. http로 html 파일에 액세스 할 때 아무런 문제가 없습니다. 나는 단지 HttpXMLRequest를 사용할 수있다. 그러나 HTML이 로컬 디스크에서 읽혀질 때 (대부분의 데스크탑 브라우저에서 File/Open과 같이 HttpXMLRequest가 작동하지 않는 것처럼 보입니다.) Java Applet을 사용 했었지만 (a) (b) 자바 스크립트 만 사용하는 솔루션을 원합니다. 자바가없고 플래시도 없습니다.html이 로컬 인 경우 JavaScript를 사용하여 로컬 파일을 읽는 방법

+0

코스 난의 작동하지 않습니다. httpxmlrequest는 HTTP 요청을 수행합니다. 'file : ///'urls로 작업 할 때 웹 서버가 없기 때문에 실제로 http 요청을 할 방법이 없습니다. –

+0

duplicate http://stackoverflow.com/questions/585234/how-to-read-and-write-into-file-using-javascript –

+1

@MarcB'XMLHttpRequest'는'file :'리소스를 올바르게 타이핑하는 것과 똑같이 처리합니다 주소 표시 줄. 유일한 차이점은'file :'scheme의 origin-policy 규칙이 다르다는 것입니다. 실제 HTTP 요청이 없다는 것과 아무 관련이 없습니다. – apsillers

답변

0

HttpXMLRequest는 HTTP 요청을 만듭니다. 웹 서버 없이는 불가능하지만 그렇지 않습니다. 로컬 호스트 서버를 설정하기가 어렵습니다.

달리 제안 할만한 다른 의견의 사람들이 있지만, 기본/사전 설치된 apache 서버를 사용하지 않는 경우 Windows 컴퓨터에 대한 선호도는 EasyPHP http://www.easyphp.org/과 XAMP입니다.

+0

웹 서버를 사용하는 것이 좋은 조언이지만 전체 답변은 여기에서 제안하는 것보다 훨씬 미묘한 차이가 있습니다. MDN의 [XHR 페이지] (https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest)에서 : "* 이름에도 불구하고,'XMLHttpRequest'는 HTTP 이외의 프로토콜을 지원합니다 ('file' * "브라우저는 파일 액세스, HTTP 요청 또는 FTP 요청 일 수있는 리소스를 가져 오는 데 사용되는 특정 메커니즘을 추상화합니다. 그러나, 동일한 출처 정책은'file' 자원에 대해'http' 자원을위한 것보다 완전히 다르게 적용됩니다. – apsillers

+0

XMLHpptRequest에 대한 동일한 사이트 정책, 특히 file : protocol에 대한 설명이있는 사람은 누구입니까? –

+0

html/javascript에서 응용 프로그램을 배포하는 것에 대한 좋은 점 중 하나는 크로스 플랫폼이며 보안상의 허점이 없다는 것입니다. 오프라인 모드에서 내 웹 앱을 사용할 수 있도록 모든 사용자 컴퓨터에 웹 서버를 설치해야하는 경우, 피할 수만 있다면 오히려 그렇게하지 않을 것입니다. –

0

여기에 파일을 자바 스크립트로 읽는 방법이 있지만 AJAX 스타일 요청만으로 제한된다면 현재 명확하지 않습니다. 어쨌든, 당신이 그 방법에만 국한되지 않는다면 FileReader을 사용할 수 있습니다.

다음 예제에서는 readAsDataURL을 사용하지만 다른 나열된 방법 중 하나를 사용할 수 있습니다.

void readAsArrayBuffer(in Blob blob); Requires Gecko 7.0 
void readAsBinaryString(in Blob blob); 
void readAsDataURL(in Blob file); 
void readAsText(in Blob blob, [optional] in DOMString encoding); 

다음은 파일을로드 한 다음 base64로 변환하고 결과 문자열을 표시하는 예제입니다.

CSS

#progress_bar { 
    margin: 10px 0; 
    padding: 3px; 
    border: 1px solid #000; 
    font-size: 14px; 
    clear: both; 
    opacity: 0; 
    -moz-transition: opacity 1s linear; 
    -o-transition: opacity 1s linear; 
    -webkit-transition: opacity 1s linear; 
} 
#progress_bar.loading { 
    opacity: 1.0; 
} 
#progress_bar .percent { 
    background-color: #99ccff; 
    height: auto; 
    width: 0; 
} 
#display { 
    width: 500px; 

높이 : 150 픽셀; }

HTML

<input type="file" id="files" name="file" /> 
<button id="cancel">Cancel read</button> 
<div id="progress_bar"> 
    <div class="percent">0%</div> 
</div> 
<div>Base64 encoded result</div> 
<textarea id="display"></textarea> 

자바 스크립트

/*jslint sub: true, maxerr: 50, indent: 4, browser: true */ 
/*global */ 

(function() { 
    "use strict"; 

    var reader, 
    progress = document.querySelector(".percent"), 
     display = document.getElementById("display"), 
     iFiles = document.getElementById("files"), 
     bCancel = document.getElementById("cancel"), 
     dropZone = document.getElementById("drop_zone"), 
     filebox = document.getElementById("filebox"), 
     list = document.getElementById("list"); 

    function abortRead() { 
     if (reader) { 
      reader.abort(); 
     } 
    } 

    function errorHandler(evt) { 
     switch (evt.target.error.code) { 
      case evt.target.error.NOT_FOUND_ERR: 
       alert("File Not Found!"); 
       break; 
      case evt.target.error.NOT_READABLE_ERR: 
       alert("File is not readable"); 
       break; 
      case evt.target.error.ABORT_ERR: 
       break; // noop 
      default: 
       alert("An error occurred reading this file."); 
     }; 
    } 

    function updateProgress(evt) { 
     // evt is an ProgressEvent. 
     if (evt.lengthComputable) { 
      var percentLoaded = Math.round((evt.loaded/evt.total) * 100); 
      // Increase the progress bar length. 
      if (percentLoaded < 100) { 
       progress.style.width = percentLoaded + "%"; 
       progress.textContent = percentLoaded + "%"; 
      } 
     } 
    } 

    function handleFileSelect(evt) { 
     // Reset progress indicator on new file selection. 
     progress.style.width = "0%"; 
     progress.textContent = "0%"; 

     reader = new FileReader(); 
     reader.onerror = errorHandler; 
     reader.onprogress = updateProgress; 
     reader.onabort = function (e) { 
      alert('File read cancelled'); 
     }; 

     reader.onloadstart = function (e) { 
      document.getElementById('progress_bar').className = 'loading'; 
     }; 

     reader.onload = function (e) { 
      // Ensure that the progress bar displays 100% at the end. 
      progress.style.width = "100%"; 
      progress.textContent = "100%"; 
      setTimeout("document.getElementById('progress_bar').className='';", 2000); 
      display.value = e.target.result; 
     } 

     // Read in the image file as a binary string. 
     reader.readAsDataURL(evt.target.files[0]); 
    } 

    iFiles.addEventListener("change", handleFileSelect, false); 
    bCancel.addEventListener("click", abortRead, false); 
}()); 

jsfiddle

업데이트의 경우 : W3C 파일 API에서 - 작업 초안

Security Considerations

This specification allows web content to read files from the underlying file system, as well as provides a means for files to be accessed by unique identifiers, and as such is subject to some security considerations. This specification also assumes that the primary user interaction is with the element of HTML forms [HTML], and that all files that are being read by FileReader objects have first been selected by the user. Important security considerations include preventing malicious file selection attacks (selection looping), preventing access to system-sensitive files, and guarding against modifications of files on disk after a selection has taken place.

+0

내 유일한 제한점은 최근의 주요 데스크톱 브라우저에서 작동하는 솔루션을 원합니다. 내 오래된 Java 기반 메소드는 Mac의 Safari에서 실패합니다. HttpXMLRequest는 Moz와 Safari에서 동일한 기원 정책으로 인해 실패 할 수 있습니다. –

+0

FileReader는 사용자의 입력에 의존하는 것 같습니다. 필자의 경우 파일에 대한 상대 경로는 문자열입니다. –

+0

나는 이것이 그 방법의 보안의 일부라고 생각한다. – Xotic750

관련 문제