본문 바로가기
개발/Flutter

[Flutter] 플러터 웹뷰 환경 파일 다운로드 구현하기

by devhooney 2024. 9. 30.
728x90

 

 

 

 

웹뷰 환경에서 파일 다운로드 구현하기!

 

 

 

 

 

 

먼저 웹뷰 라이브러리를 사용해야 한다.

 

마지막 포스팅에서 사용했던 웹뷰 사용 기준으로 한다.

 

[Flutter] 플러터 웹뷰 사용하기 (2) (tistory.com)

 

[Flutter] 플러터 웹뷰 사용하기 (2)

플러터 웹뷰 구현하기 !  지난번에 사용한 라이브러리는 rtc가 허용이 안되어서 마이크를 사용해야하는데 그 기능이 동작하지 않았다. 그래서 다른 웹뷰 라이브러리를 사용했는데, 이건  flutt

devhooney.tistory.com

 

 

 

 

광고

 

 

728x90

 

 

 

1. 라이브러리 설치

 

flutter pub add flutter_downloader

 

 

 

2. 경로 가져와주는 라이브러리 설치

 

flutter pub add path_provider

 

 

 

3. 로딩바 상태바 라이브러리 설치

 

flutter pub add sn_progress_dialog

 

  WidgetsFlutterBinding.ensureInitialized();
  await FlutterDownloader.initialize(
    debug: true,
    ignoreSsl: false,
  );
  
  ...(생략)...


child: InAppWebView(
              onPermissionRequest: (controller, permissionRequest) async {
                return PermissionResponse(
                    resources: permissionRequest.resources,
                    action: PermissionResponseAction.GRANT);
              },
     ...(생략)...
              // 파일 다운로드
              onDownloadStartRequest: (controller, request) async {
                debugPrint('!!!DownloadStart!!!');
                WebUri webUri = request.url;
                String? fileName = webUri.queryParameters['fileNm'];
                bool isGranted = true;

                // 공용 경로 설정 ( iOS 와 안드로이드 구분)
                Directory directory = await getApplicationDocumentsDirectory();
                if (Platform.isAndroid) {
                  int androidVersion = await checkAndroidVersion();
                  if (androidVersion <= 32) {
                    PermissionStatus status = await requestStoragePermission();
                    isGranted = status.isGranted;
                  }
                  directory = Directory("/storage/emulated/0/Download/");
                }

                if (isGranted) {
                  // Create new folder and download the file (새 폴더의 전체 경로 생성)
                  final newFolderPath = directory.path; //p.join(directory.path, "Bricks_Edu");
                  final newDirectory = Directory(newFolderPath);
                  if (!await newDirectory.exists()) {
                    await newDirectory.create(recursive: true);
                    debugPrint("Directory created at $newFolderPath");
                  }
                  // 파일 경로 생성
                  fileName ??= request.suggestedFilename!;
                  fileName = Uri.decodeComponent(fileName);
                  String newName = "";

                  if (Platform.isAndroid || Platform.isIOS) {
                    newName = await _getUniqueFileName(newDirectory.path, fileName);
                  } else {
                    throw UnsupportedError("No supported platform!");
                  }

                  // Show progress dialog
                  progressDialog = ProgressDialog(
                    context: context,
                  );
                  progressDialog?.show(
                    max: 100, 
                    msg: 'File Downloading...',
                    progressBgColor: Colors.transparent,
                    cancel: Cancel(
                      cancelClicked: () {
                        // ex: cancel the download
                      },
                    )
                  );

                  await FlutterDownloader.enqueue(
                    url: request.url.toString(),
                    savedDir: newDirectory.path,
                    fileName: newName,
                    saveInPublicStorage:
                        Platform.isAndroid, // 안드로이드에서만 퍼블릭 저장소 사용
                    showNotification: true,
                    openFileFromNotification: true,
                  );
                }
              },
            ),

 

 

 

 

일단 난 이렇게 구현했다.

이렇게 하면 ios, 안드로이드에서 파일 다운로드가 진행된다.

중복된 이름으로 다운로드가 되면 확장자 뒤에 번호가 생겨서 파일이 안열리는 문제가 발생해서

그거만 처리해주는 함수를 추가했다.

 

 

728x90

'개발 > Flutter' 카테고리의 다른 글

[Flutter] 플러터 웹뷰 사용하기 (2)  (184) 2024.07.09
[Flutter] 플러터 웹뷰 사용하기  (201) 2024.07.03
[Flutter] 플러터 권한 얻기  (159) 2024.07.01
[Flutter] 플러터 앱 이름 변경하기  (136) 2024.06.28
[Flutter] 플러터 .env 사용하기  (136) 2024.06.26