Tistory View

반응형

JSZip Instance만들기

압축을 풀기위해 이제 JSZip인스턴스를 만들어보자. 이 곳에는 zip파일의 내부정보가 저장되어 이 것을 통해 파일목록을 뽑아내거나 특정파일을 압축해제해야한다.

 

서버에서 zip파일을 가져와서 zip 인스턴스를 만들자.

var zipInst = null;
// 서버에서 'Zip파일 uri'을 땡겨온다.
JSZipUtils.getBinaryContent(
	'Zip파일 uri',
	function(err, data)  // 서버에서 당겨온 파일내용이 data에 들어있게 된다.
	{
		if(err) {
			throw err; // or handle err
		}
		
        // data를 분석하여 Zip파일내의 파일정보를 추출할 것이다.
    	JSZip.loadAsync( data ).then(
			// zip : JSZip의 오브젝트로 Zip파일의 모든 정보를 담고 있다.    
    		function ( zip ) 
	    	{
				// zip이 우리가 만들려는 인스턴스다.
                zipInst = zip;
			}
		);
	}
);

서버에서 파일을 Ajax로 가지고 오는 코드이다. 이 작업 때문에 JSZipUtils가 필요한 것일 뿐, 실제로 JSZipUtils가 쓰기 싫다면 Ajax로 만들어 써도 된다.

 

로컬파일로 Zip Instance만들기

사용자가 Zip파일을 지정하면 그 파일로 Zip Instance를 만들어보자.

// script
function zip_create_instace( evt ) {
	var file = document.getElementById("fileForUpload").files[0];
		
		if (file) {
	    var reader = new FileReader();
	    reader.readAsArrayBuffer(file);
	    reader.onload = function (evt) {
	    	
			JSZip.loadAsync( evt.target.result ).then(
				function ( zip ) 
		  		{
					zipInst = zip;
				}
			);
	    }
	    reader.onerror = function (evt) {
	        console.log('not zip file');
	    }
		}
		else {
			console.log('file is null');
		}
}


// html
Zip파일 : <input id="fileForUpload" type="file" name="zipfilename" />
<input  type="button" onclick="zip_create_instace( event )" value="create zip instance" />

실제 파일을 서버에 업로드를 하지않고 브라우저에서 파일의 내용을 읽어서 zip 인스턴스를 만들게 된다.

(뒷부분에서 이야기 하겠지만, 로컬파일을 사용자가 지정하지 않는 이상 읽어낼 방법은 사실상 없다.)

 

 

zip파일내의 파일목록 뽑기

zip instance를 만들었으니 이제 원하는 작업을 할 수가 있다. 우선 zip파일내의 파일목록을 뽑아보자

function zip_list_filenames( zip ) 
{
	
	// Zip파일내의 모든 파일을 순회한다.(압축을 푼것이 아니고 zip파일내의 파일목록)
	zip.forEach( 
		function (relativePath, entry )
		{									
			console.log( entry.name );							
			console.log( entry.dir ? 'dir' : 'file' );
			console.log( entry._data.compressedSize   == null ? 0 : entry._data.compressedSize   );
			console.log( entry._data.uncompressedSize == null ? 0 : entry._data.uncompressedSize );
			console.log( entry._data.crc32            == null ? 0 : entry._data.crc32            );
		}
	);
}

"_"(언더스코어)가 있는 것을 건드려서 좀 찜찜하다, 현재 사용하고 있는 버전은 이 방식으로 동작하지만, 차후 버전에서는 동작이 안될 수 있으니, _data는 건들지 말기를 권장한다.

 

zip파일은 디렉토리의 경우 entry명의 맨 뒤에 '/'가 붙어있다.

이 '/'를 이용하여 파일인지 디렉토리인지 구분을 하도록 되어있다.

 

 

 

 

반응형
Replies
NOTICE
RECENT ARTICLES
RECENT REPLIES
Total
Today
Yesterday
LINK
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Article Box