updates readme and changelog and adds support for multiple path selection on Android

This commit is contained in:
Miguel Ruivo 2019-03-08 01:42:07 +00:00
parent 96075a06f1
commit aa2cfc95bd
10 changed files with 183 additions and 84 deletions

View File

@ -1,3 +1,17 @@
## 1.3.0
**Breaking changes**
* `FileType.CAMERA` is no longer available, if you need it, you can use this package along with [image_picker](https://pub.dartlang.org/packages/image_picker).
**New features**
* You can now pick multiple files by using the `getMultiFilePath()` method which will return a `Map<String,String>` with all paths from selected files, where the key matches the file name and the value its path. Optionally, it also supports filtering by file extension, otherwise all files will be selectable. Nevertheless, you should keep using `getFilePath()` for single path picking.
* You can now use `FileType.AUDIO` to pick audio files. In iOS this will let you select from your music library. Paths from DRM protected files won't be loaded (see README for more details).
**Bug fixes and updates**
* This package is no longer attached to the [image_picker](https://pub.dartlang.org/packages/image_picker), and because of that, camera permission is also no longer required.
* Fixes an issue where sometimes the _InputStream_ wasn't being properly closed. Also, its exception is now being forward to the plugin caller.
* Fixes an issue where the picker, when canceled, wasn't calling the result callback on the underlying platforms.
## 1.2.0
**Breaking change**

View File

@ -10,38 +10,63 @@ File picker plugin alows you to use a native file explorer to load absolute file
First, add *file_picker* as a dependency in [your pubspec.yaml file](https://flutter.io/platform-plugins/).
```
file_picker: ^1.2.0
file_picker: ^1.3.0
```
## Android
Add `<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>` to your app `AndroidManifest.xml` file.
Add `<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>` to your app `AndroidManifest.xml` file. This is required due to file caching when a path is required from a remote file (eg. Google Drive).
## iOS
Since we are using *image_picker* as a dependency from this plugin to load paths from gallery and camera, we need the following keys to your _Info.plist_ file, located in `<project root>/ios/Runner/Info.plist`:
Based on the location of the files that you are willing to pick paths, you may need to add some keys to your iOS app's _Info.plist_ file, located in `<project root>/ios/Runner/Info.plist`:
* `NSPhotoLibraryUsageDescription` - describe why your app needs permission for the photo library. This is called _Privacy - Photo Library Usage Description_ in the visual editor.
* `NSCameraUsageDescription` - describe why your app needs access to the camera. This is called _Privacy - Camera Usage Description_ in the visual editor.
* `NSMicrophoneUsageDescription` - describe why your app needs access to the microphone, if you intend to record videos. This is called _Privacy - Microphone Usage Description_ in the visual editor.
* `UIBackgroundModes` with the `fetch` and `remote-notifications` keys - describe why your app needs to access background taks, such downloading files (from cloud services) when not cached to locate path. This is called _Required background modes_, with the keys _App download content from network_ and _App downloads content in response to push notifications_ respectively in the visual editor (since both methods aren't actually overriden, not adding this property/keys may only display a warning, but shouldn't prevent its correct usage).
* **_NSAppleMusicUsageDescription_** - Required if you'll be using the `FileType.AUDIO`. Describe why your app needs permission to access music library. This is called _Privacy - Media Library Usage Description_ in the visual editor.
* **_NSPhotoLibraryUsageDescription_** - Required if you'll be using the `FileType.IMAGE` or `FileType.VIDEO`. Describe why your app needs permission for the photo library. This is called _Privacy - Photo Library Usage Description_ in the visual editor.
* **_UIBackgroundModes_** with the **_fetch_** and **_remote-notifications_** keys - Required if you'll be using the `FileType.ANY` or `FileType.CUSTOM`. Describe why your app needs to access background taks, such downloading files (from cloud services) when not cached to locate path. This is called _Required background modes_, with the keys _App download content from network_ and _App downloads content in response to push notifications_ respectively in the visual editor (since both methods aren't actually overriden, not adding this property/keys may only display a warning, but shouldn't prevent its correct usage).
## Usage
There's only one method within this package
`FilePicker.getFilePath()`
this receives 2 optional parameters, the `fileType` and a `fileExtension` to be used along with `FileType.CUSTOM`.
So, 2 basically usages may be:
There are only two methods that should be used with this package:
#### `FilePicker.getFilePath()`
Will let you pick a **single** file. This receives two optional parameters: the `fileType` for specifying the type of the picker and a `fileExtension` parameter to filter selectable files. The available filters are:
* `FileType.ANY` - Will let you pick all available files.
* `FileType.CUSTOM` - Will let you pick a single path for the extension matching the `fileExtension` provided.
* `FileType.IMAGE` - Will let you pick a single image file. Opens gallery on iOS.
* `FileType.VIDEO` - WIll let you pick a single video file. Opens gallery on iOS.
* `FileType.AUDIO` - Will let you pick a single audio file. Opens music on iOS. Note that DRM protected files won't provide a path, `null` will be returned instead.
#### `FilePicker.getMultiFilePath()`
Will let you select **multiple** files and retrieve its path at once. Optionally you can provide a `fileExtension` parameter to filter the allowed selectable files.
Will return a `Map<String,String>` with the files name (`key`) and corresponding path (`value`) of all selected files.
Picking multiple paths from iOS gallery (image and video) aren't currently supported.
#### Usages
So, a few basically usages can be as follow:
```
await FilePicker.getFilePath(type: FileType.ANY); // will display all file types
await FilePicker.getFilePath(type: FileType.CUSTOM, fileExtension: 'svg'); // will filter and display only files with SVG extension.
String filePath;
filePath = await FilePicker.getFilePath(type: FileType.ANY); // will let you pick one file, from all extensions
filePath = await FilePicker.getFilePath(type: FileType.CUSTOM, fileExtension: 'svg'); // will filter and only let you pick files with svg extension.
Map<String,String> filesPaths;
filePaths = await FilePicker.getMultiFilePath(); // will let you pick multiple files of any format at once
filePaths = await FilePicker.getMultiFilePath(fileExtension: 'pdf'); // will let you pick multiple pdf files at once
```
**Note:** When using `FileType.CUSTOM`, unsupported extensions will throw a `MissingPluginException` that is handled by the plugin.
##### A few notes
* When using `FileType.CUSTOM`, unsupported extensions will throw a `MissingPluginException` that is handled by the plugin.
* On Android, when available, you should avoid using custom file explorers as those may prevent file extension filtering (behaving as `FileType.ANY`). In this scenario, you will need to validate it on return.
## Currently supported features
* [X] Load paths from **cloud files** (GDrive, Dropbox, iCloud)
* [X] Load path from **gallery**
* [X] Load path from **camera**
* [X] Load path from **video**
* [X] Load path from **any** type of file (without filtering)
* [X] Load path from a **custom format** by providing a file extension (pdf, svg, zip, etc.)
* [X] Load path from **multiple files** with an optional file extension
* [X] Load path from **gallery**
* [X] Load path from **audio**
* [X] Load path from **video**
* [X] Load path from **any** file type (without filtering, just pick what you want)
## Demo App
@ -100,3 +125,4 @@ For help getting started with Flutter, view our online
[documentation](https://flutter.io/).
For help on editing plugin code, view the [documentation](https://flutter.io/platform-plugins/#edit-code).

View File

@ -17,6 +17,7 @@ import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import io.flutter.plugin.common.MethodCall;
@ -37,6 +38,7 @@ public class FilePickerPlugin implements MethodCallHandler {
private static Result result;
private static Registrar instance;
private static String fileType;
private static boolean isMultipleSelection = false;
/** Plugin registration. */
public static void registerWith(Registrar registrar) {
@ -50,51 +52,42 @@ public class FilePickerPlugin implements MethodCallHandler {
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
if (data != null) {
if(data.getClipData() != null) {
int count = data.getClipData().getItemCount();
int currentItem = 0;
ArrayList<String> paths = new ArrayList<>();
while(currentItem < count) {
final Uri currentUri = data.getClipData().getItemAt(currentItem).getUri();
String path = FileUtils.getPath(currentUri, instance.context());
paths.add(path);
Log.i(TAG, "[MultiFilePick] File #" + currentItem + " - URI: " +currentUri.getPath());
currentItem++;
}
result.success(paths);
} else if (data != null) {
Uri uri = data.getData();
Log.i(TAG, "URI:" +data.getData().toString());
Log.i(TAG, "[SingleFilePick] File URI:" +data.getData().toString());
String fullPath = FileUtils.getPath(uri, instance.context());
String cloudFile = null;
if(fullPath == null)
{
FileOutputStream fos = null;
cloudFile = instance.activeContext().getCacheDir().getAbsolutePath() + "/" + FileUtils.getFileName(uri, instance.activeContext());
try {
fos = new FileOutputStream(cloudFile);
try {
BufferedOutputStream out = new BufferedOutputStream(fos);
InputStream in = instance.activeContext().getContentResolver().openInputStream(uri);
byte[] buffer = new byte[8192];
int len = 0;
while ((len = in.read(buffer)) >= 0) {
out.write(buffer, 0, len);
}
out.flush();
} finally {
fos.getFD().sync();
}
} catch (Exception e) {
try {
fos.close();
} catch(IOException ex) {
result.error(TAG, "Failed to close file streams: " + e.getMessage(),null);
}
result.error(TAG, "Failed to retrieve path: " + e.getMessage(),null);
}
Log.i(TAG, "Remote file loaded and cached at:" + cloudFile);
fullPath = cloudFile;
if(fullPath == null) {
fullPath = FileUtils.getUriFromRemote(instance.activeContext(), uri, result);
}
Log.i(TAG, "Absolute file path:" + fullPath);
result.success(fullPath);
}
if(fullPath != null) {
Log.i(TAG, "Absolute file path:" + fullPath);
result.success(fullPath);
} else {
result.error(TAG, "Failed to retrieve path." ,null);
}
}
return true;
} else if(requestCode == REQUEST_CODE && resultCode == Activity.RESULT_CANCELED) {
result.success(null);
return true;
}
result.error(TAG, "Unknown activity error, please report issue." ,null);
return false;
}
});
@ -116,8 +109,9 @@ public class FilePickerPlugin implements MethodCallHandler {
public void onMethodCall(MethodCall call, Result result) {
this.result = result;
fileType = resolveType(call.method);
isMultipleSelection = (boolean)call.arguments;
if(fileType == null){
if(fileType == null) {
result.notImplemented();
} else {
startFileExplorer(fileType);
@ -132,7 +126,6 @@ public class FilePickerPlugin implements MethodCallHandler {
}
private static void requestPermission() {
Activity activity = instance.activity();
Log.i(TAG, "Requesting permission: " + permission);
String[] perm = { permission };
@ -180,6 +173,7 @@ public class FilePickerPlugin implements MethodCallHandler {
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath() + File.separator);
intent.setDataAndType(uri, type);
intent.setType(type);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, isMultipleSelection);
intent.addCategory(Intent.CATEGORY_OPENABLE);
Log.d(TAG, "Intent: " + intent.toString());

View File

@ -11,7 +11,13 @@ import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.MimeTypeMap;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import io.flutter.plugin.common.MethodChannel;
/**
* Credits to NiRRaNjAN from utils extracted of in.gauriinfotech.commons;.
@ -19,7 +25,7 @@ import android.webkit.MimeTypeMap;
public class FileUtils {
private static final String tag = "FilePickerUtils";
private static final String TAG = "FilePickerUtils";
public static String getPath(final Uri uri, Context context) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
@ -38,20 +44,20 @@ public class FileUtils {
@TargetApi(19)
private static String getForApi19(Context context, Uri uri) {
Log.e(tag, " --- API 19 URI --- " + uri);
Log.e(TAG, "Getting for API 19 or above" + uri);
if (DocumentsContract.isDocumentUri(context, uri)) {
Log.e(tag, "--- Document URI ---");
Log.e(TAG, "Document URI");
if (isExternalStorageDocument(uri)) {
Log.e(tag, "--- External Document URI ---");
Log.e(TAG, "External Document URI");
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
Log.e(tag, "--- Primary External Document URI ---");
Log.e(TAG, "Primary External Document URI");
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
} else if (isDownloadsDocument(uri)) {
Log.e(tag, "--- Downloads External Document URI ---");
Log.e(TAG, "Downloads External Document URI");
final String id = DocumentsContract.getDocumentId(uri);
if (!TextUtils.isEmpty(id)) {
@ -71,26 +77,26 @@ public class FileUtils {
return path;
}
} catch (Exception e) {
Log.e(tag, "Something went wrong while retrieving document path: " + e.toString());
Log.e(TAG, "Something went wrong while retrieving document path: " + e.toString());
}
}
}
} else if (isMediaDocument(uri)) {
Log.e(tag, "--- Media Document URI ---");
Log.e(TAG, "Media Document URI");
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
Log.e(tag, "--- Image Media Document URI ---");
Log.i(TAG, "Image Media Document URI");
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
Log.e(tag, "--- Video Media Document URI ---");
Log.i(TAG, "Video Media Document URI");
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
Log.e(tag, "--- Audio Media Document URI ---");
Log.i(TAG, "Audio Media Document URI");
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
@ -102,13 +108,13 @@ public class FileUtils {
return getDataColumn(context, contentUri, selection, selectionArgs);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
Log.e(tag, "--- NO DOCUMENT URI - CONTENT ---");
Log.e(TAG, "NO DOCUMENT URI - CONTENT");
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
Log.e(tag, "--- No DOCUMENT URI - FILE ---");
Log.e(TAG, "No DOCUMENT URI - FILE");
return uri.getPath();
}
return null;
@ -169,6 +175,43 @@ public class FileUtils {
return result;
}
public static String getUriFromRemote(Context context, Uri uri, MethodChannel.Result result) {
FileOutputStream fos = null;
String cloudFile = context.getCacheDir().getAbsolutePath() + "/" + FileUtils.getFileName(uri, context);
try {
fos = new FileOutputStream(cloudFile);
try {
BufferedOutputStream out = new BufferedOutputStream(fos);
InputStream in = context.getContentResolver().openInputStream(uri);
byte[] buffer = new byte[8192];
int len = 0;
while ((len = in.read(buffer)) >= 0) {
out.write(buffer, 0, len);
}
out.flush();
} finally {
fos.getFD().sync();
}
} catch (Exception e) {
try {
fos.close();
} catch(IOException ex) {
Log.e(TAG, "Failed to close file streams: " + e.getMessage(),null);
return null;
}
Log.e(TAG, "Failed to retrieve path: " + e.getMessage(),null);
return null;
}
Log.i(TAG, "Remote file loaded and cached at:" + cloudFile);
return cloudFile;
}
private static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());

View File

@ -30,15 +30,15 @@ class _FilePickerDemoState extends State<FilePickerDemo> {
if (_pickingType != FileType.CUSTOM || _hasValidMime) {
try {
if (_multiPick) {
_path = null;
_paths = await FilePicker.getMultiFilePath(fileExtension: _extension);
print("cenas");
} else {
_paths = null;
_path = await FilePicker.getFilePath(type: _pickingType, fileExtension: _extension);
}
} on PlatformException catch (e) {
print("Unsupported operation" + e.toString());
}
if (!mounted) return;
setState(() {
@ -90,7 +90,15 @@ class _FilePickerDemoState extends State<FilePickerDemo> {
value: FileType.CUSTOM,
),
],
onChanged: (value) => setState(() => _pickingType = value)),
onChanged: (value) => setState(() {
_pickingType = value;
if (_pickingType != FileType.CUSTOM && _pickingType != FileType.ANY) {
_multiPick = false;
}
if (_pickingType != FileType.CUSTOM) {
_controller.text = _extension = '';
}
})),
),
_pickingType == FileType.CUSTOM
? new TextFormField(
@ -131,7 +139,7 @@ class _FilePickerDemoState extends State<FilePickerDemo> {
style: new TextStyle(fontWeight: FontWeight.bold),
),
new Text(
_path ?? _paths?.values?.map((path) => path + '\n\n').toString() ?? '...',
_path ?? ((_paths != null && _paths.isNotEmpty) ? _paths.values.map((path) => path + '\n\n').toString() : '...'),
textAlign: TextAlign.center,
softWrap: true,
textScaleFactor: 0.85,

View File

@ -77,7 +77,7 @@
if (@available(iOS 11.0, *)) {
self.pickerController.allowsMultipleSelection = allowsMultipleSelection;
} else if(allowsMultipleSelection) {
NSLog(@"Multiple file selection is only supported on iOS 11 and above. Single selection will be used.");
Log(@"Multiple file selection is only supported on iOS 11 and above. Single selection will be used.");
}
self.pickerController.delegate = self;
@ -171,7 +171,7 @@ didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls{
[mediaPicker dismissViewControllerAnimated:YES completion:NULL];
NSURL *url = [[[mediaItemCollection items] objectAtIndex:0] valueForKey:MPMediaItemPropertyAssetURL];
if(url == nil) {
NSLog(@"Couldn't retrieve the audio file path, either is not locally downloaded or the file DRM protected.");
Log(@"Couldn't retrieve the audio file path, either is not locally downloaded or the file DRM protected.");
}
_result([url absoluteString]);
}
@ -179,16 +179,22 @@ didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls{
#pragma mark - Actions canceled
- (void)mediaPickerDidCancel:(MPMediaPickerController *)controller {
Log(@"FilePicker canceled");
_result(nil);
_result = nil;
[controller dismissViewControllerAnimated:YES completion:NULL];
}
- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller {
Log(@"FilePicker canceled");
_result(nil);
_result = nil;
[controller dismissViewControllerAnimated:YES completion:NULL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
Log(@"FilePicker canceled");
_result(nil);
_result = nil;
[picker dismissViewControllerAnimated:YES completion:NULL];
}

View File

@ -5,6 +5,13 @@
// Created by Miguel Ruivo on 05/12/2018.
//
#import <MobileCoreServices/MobileCoreServices.h>
#ifdef DEBUG
#define Log(fmt, ...) NSLog((@"\n\n***** " fmt @"\n* %s [Line %d]\n\n\n"), ##__VA_ARGS__, __PRETTY_FUNCTION__, __LINE__)
#else
#define Log(fmt, ...)
#endif
@interface FileUtils : NSObject
+ (NSString*) resolveType:(NSString*)type;
+ (NSArray*) resolvePath:(NSArray<NSURL *> *)urls;

View File

@ -19,7 +19,7 @@
CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[format pathExtension], NULL);
NSString * UTIString = (__bridge NSString *)(UTI);
CFRelease(UTI);
NSLog(@"Custom file type: %@", UTIString);
Log(@"Custom file type: %@", UTIString);
return [UTIString containsString:@"dyn."] ? nil : UTIString;
}

View File

@ -16,10 +16,12 @@ class FilePicker {
static const MethodChannel _channel = const MethodChannel('file_picker');
static const String _tag = 'FilePicker';
FilePicker._();
static Future<dynamic> _getPath(String type, [bool multipleSelection = false]) async {
try {
dynamic result = await _channel.invokeMethod(type, multipleSelection);
if (multipleSelection) {
if (result != null && multipleSelection) {
if (result is String) {
result = [result];
}
@ -43,7 +45,7 @@ class FilePicker {
/// If provided, it will be use the `FileType.CUSTOM` for that [fileExtension].
/// If not, `FileType.ANY` will be used and any combination of files can be multi picked at once.
static Future<Map<String, String>> getMultiFilePath({String fileExtension}) async =>
await _getPath(fileExtension != null ? (_kCustomType + fileExtension) : 'ANY', true);
await _getPath(fileExtension != null && fileExtension != '' ? (_kCustomType + fileExtension) : 'ANY', true);
/// Returns an absolute file path from the calling platform
///

View File

@ -1,6 +1,6 @@
name: file_picker
description: A plugin that allows you to pick absolute paths from diferent file types.
version: 1.2.0
description: A plugin that allows you to filter and pick absolute paths for diferent file extensions.
version: 1.3.0
author: Miguel Ruivo <miguelpruivo@outlook.com>
homepage: https://github.com/miguelpruivo/plugins_flutter_file_picker
@ -8,8 +8,7 @@ homepage: https://github.com/miguelpruivo/plugins_flutter_file_picker
dependencies:
flutter:
sdk: flutter
meta: ^1.1.5
environment:
sdk: ">=2.0.0 <3.0.0"