본문 바로가기

Flutter

[Flutter] Flutter 압축 패키지 사용

서버로부터 파일을 가져올 때 보안을 위해서 zip 파일을 가져와서 사용하기로 했다.

 

이에 따라 flutter 의 압축 패키지를 사용하기 위해 검색해보았다.

 

pub.dev/packages/archive

 

archive | Dart Package

Provides encoders and decoders for various archive and compression formats such as zip, tar, bzip2, gzip, and zlib.

pub.dev

 

글 작성 시점 좋아요 128개에 해당하는 archive 패키지를 사용하기로 했다.

 

필요한 파일은 json 인데, 이를 passward가 적용된 zip으로 압축했고 이를 get으로 가져와야한다.

httpClient의 get으로 받아온 데이터를 파일로 저장해야한다.

  static var httpClient = new HttpClient();
  Future<File> _downloadFile(String url, String filename) async {
    var request = await httpClient.getUrl(Uri.parse(url));
    var response = await request.close();
    var bytes = await consolidateHttpClientResponseBytes(response);
    String dir = (await getApplicationDocumentsDirectory()).path;
    File file = new File('$dir/$filename');
    await file.writeAsBytes(bytes);
    return file;
  }

[출처 : gist.github.com/slightfoot/6f502205aca15e3cbf461df879673b56]

 

사용자에게 보일 필요가 없는 파일이기 때문에, 앱 내부 저장소에 저장을 했다.

 

파일을 저장했으니, 이제 압축을 풀어야한다.

압축이 풀릴 경로 역시 동일한 경로로 지정한다.

      var zipFile = await _downloadFile(SERVER_ADDRESS, "test.zip");
      try {
        final directory = await getApplicationDocumentsDirectory();
        final bytes = zipFile.readAsBytesSync();
        Archive archive = ZipDecoder().decodeBytes(
          bytes,
          verify: true,
          password: "passward",
        );
        final listFile = archive[0];
        final listFileName = listFile.name;
        
        final data = listFile.content as List<int>;
        var outfile = File('${directory.path}' + listFileName)
          ..createSync(recursive: true)
          ..writeAsBytesSync(data);
        String contents = await outfile.readAsString();

 

위와 같이 하면 서버로부터 zip파일을 다운받아서 압축을 해제해서, contents를 읽어올 수 있다.

 

https 를 쓰면 굳이 이렇게 안했을텐데...https 서버 구축전까진 임시 방편으로 zip을 활용해야할 듯 하다.