분류, 패키지 및 저장소 검색

패키지 상세v0.31.0

image_downloader

인터넷에서 이미지를 다운로드하여 장치에 저장하는 Flutter 플러그인입니다.

AndroidiOS
30일 다운로드
596
좋아요
266
Pub 점수
140

패키지 설치

flutter pub add image_downloader

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

image_downloader 패키지는 인터넷에서 이미지를 가져와 안드로이드 및 iOS 기기의 로컬에 저장하도록 설계된 플러터 플러그인입니다. 네트워크 요청과 파일 저장을 효율적으로 처리하여 원격 이미지 다운로드 과정을 간소화합니다. 갤러리, 프로필 사진 관리자 또는 콘텐츠 캐싱 시스템과 같은 오프라인 이미지 접근이 필요한 앱에 적합합니다. 백그라운드 다운로드를 지원하며 진행 상황 및 완료를 추적하기 위한 콜백을 제공합니다.

사용 사례

  • 오프라인 사용을 위해 이미지 다운로드
  • 앱 콘텐츠 캐싱
  • 사용자 생성 미디어 저장
  • 이미지 갤러리 앱 만들기
  • 성능을 위한 자산 사전 로딩

주요 기능

  • Android 및 iOS 플랫폼을 지원합니다
  • 백그라운드 다운로드 기능
  • 콜백을 통한 진행 추적
  • 이미지 검색을 위한 간단한 API
  • 장치 저장소에 파일 자동 저장

적합한 대상

  • 오프라인 이미지 접근이 필요한 앱
  • 미디어 집약형 애플리케이션
  • 콘텐츠 캐싱 솔루션
  • 이미지 관리 도구
  • 경량 다운로드 도구를 찾는 개발자

고려 사항

  • 외부 저장소에 적절한 권한이 필요합니다
  • 실패한 다운로드에 대한 오류 처리가 필요할 수 있습니다
  • 큰 파일은 장치 저장소에 영향을 줄 수 있습니다
  • 초기 다운로드를 위해 네트워크 연결이 필요합니다
  • 플랫폼에서 지원하는 이미지 형식에만 제한됨

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

image_downloader

Flutter plugin that downloads images and movies on the Internet and saves to Photo Library on iOS or specified directory on Android.
This will keep Exif(DateTimeOriginal) and GPS(Latitude, Longitude).

Getting Started

ios

Add the following keys to your Info.plist file, located in /ios/Runner/Info.plist:

  • NSPhotoLibraryUsageDescription - Specifies the reason for your app to access the user’s photo library. This is called Privacy - Photo Library Usage Description in the visual editor.
  • NSPhotoLibraryAddUsageDescription - Specifies the reason for your app to get write-only access to the user’s photo library. This is called Privacy - Photo Library Additions Usage Description in the visual editor.
Android

Add this permission in AndroidManifest.xml. (If you call AndroidDestinationType#inExternalFilesDir(), This setting is not necessary.)

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Example

Basic
try {
  // Saved with this method.
  var imageId = await ImageDownloader.downloadImage("https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/flutter.png");
  if (imageId == null) {
    return;
  }

  // Below is a method of obtaining saved image information.
  var fileName = await ImageDownloader.findName(imageId);
  var path = await ImageDownloader.findPath(imageId);
  var size = await ImageDownloader.findByteSize(imageId);
  var mimeType = await ImageDownloader.findMimeType(imageId);
} on PlatformException catch (error) {
  print(error);
}

The return value is as follows.

  • imageId of the saved image if saving succeeded.
  • null if not been granted permission.
  • Otherwise it is a PlatformException.
Custom

You can specify the storage location.
(Currently, external storage is only supported on Android.)

Three directories by default are provided.

  • AndroidDestinationType.directoryDownloads -> Environment.DIRECTORY_DOWNLOADS on Android
  • AndroidDestinationType.directoryPictures -> Environment.DIRECTORY_PICTURES on Android
  • AndroidDestinationType.directoryDCIM -> Environment.DIRECTORY_DCIM on Android
  • AndroidDestinationType.directoryMovies -> Environment.DIRECTORY_MOVIES on Android

In addition, there is also custom.

For example, the following sources is stored in /storage/emulated/0/sample/custom/sample.gif.
(Depends on the device.)

await ImageDownloader.downloadImage(url,
                                    destination: AndroidDestinationType.custom('sample')                                  
                                    ..subDirectory("custom/sample.gif"),
        );

For example, the following sources is stored in /storage/emulated/0/Android/data/<applicationId>/files/sample/custom/sample.gifby calling inExternalFilesDir() .
(Depends on the device.)

 await ImageDownloader.downloadImage(url,
                                     destination: AndroidDestinationType.custom('sample')
                                     ..inExternalFilesDir()
                                     ..subDirectory("custom/sample.gif"),
         );

Note: inExternalFilesDir() will not require WRITE_EXTERNAL_STORAGE permission, but downloaded images will also be deleted when uninstalling.

Progress

You can get the progress value.
Note: On iOS, onProgressUpdate cannot get imageId.

  @override
  void initState() {
    super.initState();

    ImageDownloader.callback(onProgressUpdate: (String imageId, int progress) {
      setState(() {
        _progress = progress;
      });
    });
  }

Downloading multiple files

You can do it simply by using await .

var list = [
  "https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/bigsize.jpg",
  "https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/flutter.jpg",
  "https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/flutter_transparent.png",
  "https://raw.githubusercontent.com/wiki/ko2ic/flutter_google_ad_manager/images/sample.gif",
  "https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/flutter_no.png",
  "https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/flutter.png",
];

List<File> files = [];

for (var url in list) {
  try {
    var imageId = await ImageDownloader.downloadImage(url);
    var path = await ImageDownloader.findPath(imageId);
    files.add(File(path));
  } catch (error) {
    print(error);
  }
}
setState(() {
  _mulitpleFiles.addAll(files);
});

Preview

There is a open method to be able to immediately preview the download file.
If you call it, in the case of ios, a preview screen using UIDocumentInteractionController is displayed. In case of Android, it is displayed by Intent.

var imageId = await ImageDownloader.downloadImage(url);
var path = await ImageDownloader.findPath(imageId);
await ImageDownloader.open(path);

Note: in the case of android, to use this feature, the following settings are required.

Add the following within <application> tag in AndroidManifest.xml .

        <provider
                android:name="com.ko2ic.imagedownloader.FileProvider"
                android:authorities="${applicationId}.image_downloader.provider"
                android:exported="false"
                android:grantUriPermissions="true">
            <meta-data
                    android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/provider_paths"/>
        </provider>

Add provider_paths.xml in android/app/src/main/res/xml/ .

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

Error Handling

downloadImage()

You can determine the type of error with PlatformException#code.

In the case of HTTP status error, the code is stored.
In the case of the file format is not supported, unsupported_file is stored.
There is an important point in the case of unsupported_file.
Even unsupported files are stored in a temporary directory.
It can be retrieved with error.details ["unsupported_file_path"]; .
Note: it will be deleted when you exit the app.

ImageDownloader.downloadImage(url).catchError((error) {
  if (error is PlatformException) {
    var path = "";
    if (error.code == "404") {
      print("Not Found Error.");
    } else if (error.code == "unsupported_file") {
      print("UnSupported FIle Error.");
      path = error.details["unsupported_file_path"];
    }
  }
})

open()

If the file can not be previewed, the preview_error is stored in the code.

  await ImageDownloader.open(_path).catchError((error) {
    if (error is PlatformException) {
      if (error.code == "preview_error") {
        print(error.message);
      }
    }    
  });

Trouble Shooting

https://github.com/ko2ic/image_downloader/wiki#trouble-shooting

카테고리

소스 저장소

이 패키지를 사용하는 프로젝트