amplify-flutter icon indicating copy to clipboard operation
amplify-flutter copied to clipboard

Fatal error when trying to upload image to s3 bucket

Open mattRiddoch opened this issue 6 years ago • 15 comments

Describe the bug Unexpectedly found nil while implicitly unwrapping an Optional value: file..../ios/Pods/AmplifyPlugins/AmplifyPlugins/Storage/AWSS3StoragePlugin/AWSS3StoragePlugin+ClientBehavior.swift, line 157 passing the file from the imagepicker upload snippet:

await picker
   .getImage(source: ImageSource.gallery)
    .then((value) async {
        File fileInstance = File(value.path);
        final key = new DateTime.now().toString();
        UploadFileResult result =
            await Amplify.Storage.uploadFile(
                 key: key, local: fileInstance);
       });

crashing swift snippet (crashes on storageService):

let uploadFileOperation = AWSS3StorageUploadFileOperation(request,
                                                                  storageService: storageService,
                                                                  authService: authService,
                                                                  progressListener: progressListener,
                                                                  resultListener: resultListener)

I have an authenticated user.

To Reproduce Steps to reproduce the behavior:

  1. Pass key and file to Amplify.Storage.uploadFile
  2. Raise exception in xcode

Expected behavior I expect the file to upload.

Screenshots If applicable, add screenshots to help explain your problem.

Platform Amplify Flutter current supports iOS and Android. This issue is reproducable in (check all that apply): [] Android [x] iOS

Smartphone (please complete the following information):

  • Device: simulator 11 pro
  • OS: 13.6

mattRiddoch avatar Aug 27 '20 02:08 mattRiddoch

@mattRiddoch can you confirm that value.path is indeed a valid file path before passing it to the uploadFile() API?

Ashish-Nanda avatar Aug 28 '20 22:08 Ashish-Nanda

@Ashish-Nanda Here is what the path looks like: /Users/mattriddoch/Library/Developer/CoreSimulator/Devices/F694C06D-4AEA-490F-BE99-CB8635D94192/data/Containers/Data/Application/2F52DFEB-FD29-4F4E-A364-EEB065717896/tmp/image_picker_26878D92-6B72-499F-BB77-8DE1FFF011FC-52750-0000DACF01486E63.jpg The image is coming from the library via image_picker: ^0.6.7+4 in the simulator.

mattRiddoch avatar Aug 28 '20 22:08 mattRiddoch

Hi @mattRiddoch

I think the issue is likely coming from the image_picker library you're using. I've tried reproducing your error (using a different picker library) and have no issues uploading image files from my gallery on a iPhone SE emulator.

Could you try using the file_picker: ^1.8.0+1 in your pubspec.yaml instead to see if that works for you? We use that in our example app for picking files to upload.

fjnoyp avatar Aug 31 '20 22:08 fjnoyp

@mattRiddoch

The path of the file you provided seems fine, so not sure why you are getting the error. I also tried a clean setup today in an attempt to reproduce your issue and can confirm upload is working as expected. We are using the file_picker library @fjnoyp mentioned above. Could you give that a try based on the code in our sample app?

Let us know if you still face issues.

Ashish-Nanda avatar Sep 01 '20 02:09 Ashish-Nanda

OK! I brought in the file_picker library and am using the following uploading snippet from the example code:

void upload() async {
    try {
      print('In upload');
      // Uploading the file with options
      File local = await FilePicker.getFile(type: FileType.image);
      final key = new DateTime.now().toString();
      Map<String, String> metadata = <String, String>{};
      metadata['name'] = 'filename';
      metadata['desc'] = 'A test file';

      S3UploadFileOptions options = S3UploadFileOptions(
          accessLevel: StorageAccessLevel.guest, metadata: metadata);
      UploadFileResult result = await Amplify.Storage.uploadFile(
          key: key, local: local, options: options);
        print(result.key);
    } catch (e) {
      print('UploadFile Err: ' + e.toString());
    }
  }

Upon picking an asset I get the following error: UploadFile Err: RangeError (index): Invalid value: Valid value range is empty: 0 I did set a breakpoint prior to the upload attempt and can confirm that a valid file is being passed in?

On a side note this is the exact same error I raise when I save a file to the documents folder and attempt to upload from there as well?

mattRiddoch avatar Sep 02 '20 16:09 mattRiddoch

Hi @mattRiddoch it's strange the example code isn't working for you now as well. We've validated this code works so this issue could be related to your configuration.

Have you tried running the Amplify CLI to create a s3 bucket and performed an upload. Can you provide details on how you've generated your amplifyconfiguration.dart file?

fjnoyp avatar Sep 04 '20 18:09 fjnoyp

@mattRiddoch can you share you amplifyconfiguration.dart file?

Ashish-Nanda avatar Sep 08 '20 12:09 Ashish-Nanda

Sure thing @Ashish-Nanda

const amplifyconfig = ''' {
    "UserAgent": "aws-amplify-cli/2.0",
    "Version": "1.0",
    "auth": {
        "plugins": {
            "awsCognitoAuthPlugin": {
                "UserAgent": "aws-amplify-cli/0.1.0",
                "Version": "0.1.0",
                "IdentityManager": {
                    "Default": {}
                },
                "CredentialsProvider": {
                    "CognitoIdentity": {
                        "Default": {
                            "PoolId": "<PoolId>
                            "Region": "us-east-1"
                        }
                    }
                },
                "CognitoUserPool": {
                    "Default": {
                        "PoolId": "<PoolId>",
                        "AppClientId": "<ClientId>",
                        "AppClientSecret": "<ClientSecret>",
                        "Region": "us-east-1"
                    }
                },
                "Auth": {
                    "Default": {
                        "authenticationFlowType": "USER_SRP_AUTH"
                    }
                },
                "PinpointAnalytics": {
                    "Default": {
                        "AppId": "<AppId>",
                        "Region": "us-east-1"
                    }
                },
                "PinpointTargeting": {
                    "Default": {
                        "Region": "us-east-1"
                    }
                },
                "S3TransferUtility": {
                    "Default": {
                        "Bucket": "<BucketId>
                        "Region": "us-east-1"
                    }
                }
            }
        }
    },
    "analytics": {
        "plugins": {
            "awsPinpointAnalyticsPlugin": {
                "pinpointAnalytics": {
                    "appId": "<AppId>",
                    "region": "us-east-1"
                },
                "pinpointTargeting": {
                    "region": "us-east-1"
                }
            }
        }
    },
    "storage": {
        "plugins": {
            "awsS3StoragePlugin": {
                "bucket": "<bucketId>",
                "region": "us-east-1",
                "defaultAccessLevel": "guest"
            }
        }
    }
}''';

mattRiddoch avatar Sep 08 '20 15:09 mattRiddoch

I am having an issue identical to this one - I am configured using the example Storage application and upon uploading I also get UploadFile Err: RangeError (index): Invalid value: Valid value range is empty: 0

adamfilli avatar Sep 08 '20 18:09 adamfilli

You can try first getting a path of the file and store that in some variable then pass that value in uploadFile function like this image

Hope it helps!

Shrey29ansh avatar Sep 21 '20 21:09 Shrey29ansh

@Shrey29ansh I will give this a try soon. I have gotten a little sidetracked with other features but this is still very much an issue for me. Much appreciated.

mattRiddoch avatar Sep 21 '20 22:09 mattRiddoch

Hey @mattRiddoch have you been able to resolve this issue?

fjnoyp avatar Oct 02 '20 19:10 fjnoyp

I also got this error.

RangeError (index): Invalid value: Valid value range is empty: 0.

Now I have solved this error.

The reason was that the list "plugins" in the StorageCategory class was empty.

The problem is probably in the initial configuration of the plugins.

Here is the code before the fix.

// Add Pinpoint and Cognito Plugins
AmplifyAnalyticsPinpoint analyticsPlugin = AmplifyAnalyticsPinpoint();
AmplifyAuthCognito authPlugin = AmplifyAuthCognito();
amplifyInstance.addPlugin(authPlugins: [authPlugin]);
amplifyInstance.addPlugin(analyticsPlugins: [analyticsPlugin]);

AmplifyDataStore datastorePlugin =
AmplifyDataStore(modelProvider: ModelProvider.instance);
amplifyInstance.addPlugin(dataStorePlugins: [datastorePlugin]);

// Add this line, to include the Auth plugin.
AmplifyStorageS3 storage = AmplifyStorageS3();
amplifyInstance.addPlugin(
    authPlugins: [authPlugin],
    storagePlugins: [storage]
);

// Once Plugins are added, configure Amplify
await amplifyInstance.configure(amplifyconfig);

Here is the code after the fix.

// Add Pinpoint and Cognito Plugins
AmplifyAnalyticsPinpoint analyticsPlugin = AmplifyAnalyticsPinpoint();
AmplifyAuthCognito authPlugin = AmplifyAuthCognito();

AmplifyDataStore datastorePlugin =
AmplifyDataStore(modelProvider: ModelProvider.instance);

// Add this line, to include the Auth plugin.
AmplifyStorageS3 storage = AmplifyStorageS3();
amplifyInstance.addPlugin(
    authPlugins: [authPlugin],
    analyticsPlugins: [analyticsPlugin],
    dataStorePlugins: [datastorePlugin],
    storagePlugins: [storage]
);

// Once Plugins are added, configure Amplify
await amplifyInstance.configure(amplifyconfig);

naoyashiga avatar Dec 23 '20 01:12 naoyashiga

Hey @mattRiddoch . Sorry for the late reply.

I tested in iOS, and Android and I couldn't reproduce the issue

Feel free to test using the latest build and let us know if you got any issues

Thanks

mo-malaka avatar Apr 30 '21 19:04 mo-malaka

Hey @mattRiddoch

I am closing this issue for now as I didn't hear from you and I couldn't reproduce as per my comment above. We can reopen it if you are still facing the issue and when you provide details

Regards Mo

mo-malaka avatar May 21 '21 16:05 mo-malaka