HTML5/FileSystem

HTML5 FileSystem API

Soul-Learner 2013. 12. 20. 15:15

HTML5에서 제시하는 Javascript FileSystem API를 사용하면 웹페이지에서도 로컬 시스템의 파일 시스템에 접근하여 파일을 읽고 쓰는 일이 가능하다.

물론 파일을 생성하는 것과 파일이나 디렉토리를 이동하면서 어떤 작업을 수행하는 것도 가능해졌다.

FileSystem API는 SandBox 보안모델이 적용되어 외부로부터 로컬 시스템에 가해지는 보안상 피해를 최소화하는 범위 내에서 작동하도록 설계되었다.

FileSystem API를 통하여 생성되는 파일은 로컬 시스템에서 참조할 수 없는 영역에 생성되고 지정한 파일 이름으로 파일이 생성되는 것도 아니다. 그러므로 FileSystem API에서 사용하는 SandBox 전용 저장소는 웹브라우저 내부에서만 읽고 쓸 수 있는 저장소이므로 로컬 시스템과 관련이 없는 저장소이기 때문에 일반 사용자가 로컬 시스템에서 참조할 수 있는 영역이 아니다. 또한 보안상 위험할 수 있는 실행파일 등은 저장할 수 없도록 스펙에 정의되어 있다


참고원문: http://www.html5rocks.com/en/tutorials/file/filesystem/


HTML5가 지원하는 Javascript FileSystem API 는 다음과 같이 분류된다

  • Reading and manipulating files: File/Blob, FileList, FileReader
  • Creating and writing: Blob(), FileWriter
  • Directories and file system access: DirectoryReader,FileEntry/DirectoryEntry, LocalFileSystem

FileSystem API는 현재 Google Chrome 브라우저에서 지원하고 있으며 아래의 코드는 모두 Google Chrome 브라우저에서 테스트를 거쳤다


학습목표: 현재 로컬 시스템에 있는 파일을 로드하여 내용을 화면에 출력하고, 만약 특정 이름의 파일이 로컬 시스템의 특정 위치에서 발견되지 않는다면 서버측에 있는 동일 이름의 파일을 가져와서 로컬 시스템에 저장한다.


현재 Javascript가 실행되는 OS의 종류 알아내기

var OSName="Unknown OS";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";
if (navigator.appVersion.indexOf("Android")!=-1 OSName="Android";

document.write('Your OS: '+OSName);



현재의 브라우저가 FileSystem API를 지원하는지 확인하고 로컬시스템에 파일의 생성, 쓰기, 읽기, 삭제를 테스트하는 코드

<script>

/*  실행중 오류 발생시 호출될 콜백함수 */

function errorCallback(error) {

  var message = '';


  switch (error.message) {

    case FileError.SECURITY_ERR:

      message = 'Security Error';

      break;

    case FileError.NOT_FOUND_ERR:

      message = 'Not Found Error';

      break;

    case FileError.QUOTA_EXCEEDED_ERR:

      message = 'Quota Exceeded Error';

      break;

    case FileError.INVALID_MODIFICATION_ERR:

      message = 'Invalid Modification Error';

      break;

    case FileError.INVALID_STATE_ERR:

      message = 'Invalid State Error';

      break;

    default:

      message = 'Unknown Error';

      break;

  }

  //console.log(message);

  printMsg(message);

}


var filesystem = null;


/* 현재 브라우저가 FileSystem API를 지원하는지 확인하는 함수 */

function checkFileSystem() {

    // Handle vendor prefixes.  requestFileSystem is prefixed in Google Chrome and Opera.

    window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;

    if(window.requestFileSystem) {

        //console.log("FileSystem을 지원하는 브라우저입니다");

        printMsg("FileSystem을 지원하는 브라우저입니다");

    }

    else {

       //console.log("FileSystem을 지원하지 않는 브라우저입니다");

       printMsg("FileSystem을 지원하지 않는 브라우저입니다");

    }

}


/* FileSystem API 가 임시저장소 기능을 지원하는지 확인 */

function checkTempFileSystem() {

window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;


// Request a FileSystem (임시 저장소, 브라우저가 임의로 삭제 가능한 저장소 요청)

window.requestFileSystem(window.TEMPORARY, 1024 * 1024, 

 function(filesystem) {

  //console.log("임시저장소 기능을 지원하는 브라우저입니다");

  printMsg("임시저장소 기능을 지원하는 브라우저입니다");

 },

 function(error) {

   //console.log("임시저장소 기능을 지원하지 않는 브라우저입니다");

  printMsg("임시저장소 기능을 지원하지 않는 브라우저입니다");

 }

);

}


/* FileSystem API 가 영구저장소 기능을 지원하는지 확인 */

function checkPerFileSystem() {

// 브라우저가 임의로 삭제하지 않는 영구 저장소 요청의 경우

window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;

navigator.webkitPersistentStorage.requestQuota(

1024 * 1024 * 10,

function(grantedSize) {


// Request a file system with the new size.

window.requestFileSystem(window.PERSISTENT, grantedSize, 

function(fs) {

filesystem = fs;

//console.log("대용량 영구 저장소 요청성공");

printMsg("대용량 영구 저장소 요청성공");

// Do something with your new (larger) fs

//console.log('Opened file system: ' + fs.name);

//printMsg('Opened file system: ' + fs.name);

},

errorCallback

);

},

errorCallback

);

}


/*  로컬 시스템상에 파일을 생성함 */

function createLocalFile() {

    filesystem.root.getFile('log.txt', {create: true, exclusive: true}, 

       function(fileEntry) {

          //console.log("생성된 파일의 절대경로", fileEntry.fullPath);

          printMsg("생성된 파일의 절대경로" + fileEntry.fullPath);

       }, 

  errorCallback 

);

}


/* 로컬 시스템상의 파일에 쓰기 */

function writeLocalFile() {

filesystem.root.getFile('log.txt', {create: true, exclusive: false}, 

  function(fileEntry) {

// console.log("파일의 절대경로", fileEntry.fullPath);

printMsg("파일의 절대경로", fileEntry.fullPath);

 // Create a FileWriter object for our FileEntry (log.txt).

 fileEntry.createWriter(function(fileWriter) {

 //console.log("FileWriter 생성 성공");

 printMsg("FileWriter 생성 성공");

 fileWriter.onwriteend = function(e) { //파일에 쓰기 성공 이벤트

//console.log('파일쓰기 성공.');

printMsg('파일쓰기 성공.');

 };


 fileWriter.onerror = function(e) { //파일에 쓰기 실패 이벤트

//console.log('파일쓰기 실패: ' + e.toString());

printMsg('파일쓰기 실패: ' + e.toString());

 };


 var blob = new Blob(['사랑합니다 and\n감사합니다'], {type: 'text/plain'}, 'utf-8');

 fileWriter.write(blob);

 //fileWriter.seek(0);

 }, errorCallback); // fileWriter생성 성공/실패 이벤트 끝


  }, errorCallback ); // getFile() 성공/실패 이벤트 끝

}


/* 로컬 시스템상의 파일로부터 읽어오기 */

function readLocalFile() {

// 파일 읽기

filesystem.root.getFile('log.txt', {}, function(fileEntry) {

//console.log("파일 읽기 위해 열기 성공");

printMsg("파일 읽기 위해 열기 성공");

// Get a File object representing the file,

// then use FileReader to read its contents.

fileEntry.file( function(file) { //파일 오브젝트를 구함, 성공 이벤트

//console.log("파일 오브젝트 구하기 성공");

printMsg("파일 오브젝트 구하기 성공");

var reader = new FileReader();


reader.onloadend = function(e) {

//console.log("파일읽기 내용:"+this.result );

printMsg("파일읽기 내용:"+this.result );

};


reader.readAsText(file, 'utf-8');


}, errorCallback); // 파일 오브젝트 얻기(file()) 성공/실패 이벤트 끝

}, errorCallback); // getFile 성공/실패 이벤트 끝

// 파일 읽기 끝

}


/* 로컬 시스템상의 파일삭제 */

function removeLocalFile() {

filesystem.root.getFile('log.txt', {create: false, exclusive: false}, 

function(fileEntry) {

//console.log("삭제할 파일의 절대경로", fileEntry.fullPath);

printMsg("삭제할 파일의 절대경로", fileEntry.fullPath);

fileEntry.remove( function() { //삭제성공 이벤트

//console.log('파일삭제 성공');

printMsg('파일삭제 성공');

}, errorCallback );

}, errorCallback 

);

}


/* 위의 함수들이 실행될 때 메시지를 화면에 출력하는 함수 */

function printMsg(str) {

    document.getElementById("div1").innerHTML = "";

    document.getElementById("div1").innerHTML = str;

}


</script><br />


<div id="div1" style="border:1px solid blue; width:100%; height:2em;">  </div>



PC나 Android 폰의 Chrome 브라우저에서 아래의 버튼을 누르면 위의 내용을 테스트할 수 있다