Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FileSystemException: Cannot retrieve length of file,(OS Error: No such file or directory, errno = 2) #261

Closed
shahnawazahmed88 opened this issue Apr 29, 2020 · 44 comments
Labels
triage Further information is requested

Comments

@shahnawazahmed88
Copy link

Getting, Unhandled Exception: FileSystemException: Cannot retrieve length of file, path = '/private/var/mobile/Containers/Data/Application/0C1997E5-5243-494E-85EA-830E3248CC97/tmp/com.vassar.bluis-Inbox/https:%2Ffoodlicensing.fssai.gov.in%2FREG%2FRG_ViewReceipt.aspx?ReqID=68198366.pdf' (OS Error: No such file or directory, errno = 2)

in Android its working fine but in iOS 13.4 real device getting above exception

Issue details

  1. Platform - iOS
  2. Platform OS version - 13.4
  3. File type (filter) — pdf
  4. Detailed steps to reproduce
    Working fine in android, select any pdf file and try to upload to server in iOS real device 13.4

Error Log

2020-04-29 15:56:04.991427+0530 Runner[4358:1416983] [VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: FileSystemException: Cannot retrieve length of file, path = '/private/var/mobile/Containers/Data/Application/0C1997E5-5243-494E-85EA-830E3248CC97/tmp/com.vassar.bluis-Inbox/https:%2Ffoodlicensing.fssai.gov.in%2FREG%2FRG_ViewReceipt.aspx?ReqID=68198366.pdf' (OS Error: No such file or directory, errno = 2)
#0 _File.length. (dart:io/file_impl.dart:376:9)
#1 _rootRunUnary (dart:async/zone.dart:1134:38)
#2 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
#3 _FutureListener.handleValue (dart:async/future_impl.dart:139:18)
#4 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:680:45)
#5 Future._propagateToListeners (dart:async/future_impl.dart:709:32)
#6 Future._completeWithValue (dart:async/future_impl.dart:524:5)
#7 Future._asyncComplete. (dart:async/future_impl.dart:554:7)
#8 _rootRun (dart:async/zone.dart:1126:13)
#9 _CustomZone.run (dart:async/zone.dart:1023:19)
#10 _CustomZone.runGuarded (dart:async/zone.dart:925:7)
#11 _CustomZone.bindCallbackGuarded. (dart:async/zone.dart:965:23)
#12 _microtaskLoop (dart:async/schedule_microtask.dart:43:21)
#13 _startMicrotaskLoop (dart:async/schedule_microtask.dart:52:5)

Flutter Version details
[✓] Flutter (Channel stable, v1.12.13+hotfix.9, on Mac OS X 10.15.4 19E287,
locale en-IN)
• Flutter version 1.12.13+hotfix.9 at /Users/teja/flutter_dev/flutter
• Framework revision f139b11009 (4 weeks ago), 2020-03-30 13:57:30 -0700
• Engine revision af51afceb8
• Dart version 2.7.2

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
• Android SDK at /Users/teja/Library/Android/sdk
• Android NDK location not configured (optional; useful for native profiling
support)
• Platform android-29, build-tools 29.0.2
• Java binary at: /Applications/Android
Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build
1.8.0_202-release-1483-b49-5587405)
• All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.4.1)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 11.4.1, Build version 11E503a
• CocoaPods version 1.9.1

[✓] Android Studio (version 3.5)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin version 42.1.1
• Dart plugin version 191.8593
• Java version OpenJDK Runtime Environment (build
1.8.0_202-release-1483-b49-5587405)

[✓] Connected device (1 available)
• Shahnawaz’s iphone • d59a055eb9bbddc9be958142d9c484e3c45bbf2f • ios • iOS
13.4.1

• No issues found!

@shahnawazahmed88 shahnawazahmed88 added the new issue An issue that hasn't yet been seen from the maintainer label Apr 29, 2020
@miguelpruivo
Copy link
Owner

@shahnawazahmed88 does that happen with all files or just that one? May I ask you to try with another one? Thanks.

@miguelpruivo miguelpruivo added triage Further information is requested and removed new issue An issue that hasn't yet been seen from the maintainer labels Apr 29, 2020
@shahnawazahmed88
Copy link
Author

Yeah I tried with another pdf file "A Sample PDF.pdf", got exception

[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: FileSystemException: Cannot retrieve length of file, path = '/private/var/mobile/Containers/Data/Application/91C0B3B7-2102-49AE-9647-61904A9DB030/tmp/com.vassar.bluis-Inbox/A Sample PDF.pdf' (OS Error: No such file or directory, errno = 2)

@miguelpruivo
Copy link
Owner

@shahnawazahmed88 that stack doesn't seem to be coming from the plugin itself but with something that you might be doing afterwards.

May I ask you to post the code/lines where you got the exception? Thank you.

@shahnawazahmed88
Copy link
Author

I am not getting line number after this exception occurs, check here complete logs

2020-04-29 16:29:55.398581+0530 Runner[4401:1425062] [VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: FileSystemException: Cannot retrieve length of file, path = '/private/var/mobile/Containers/Data/Application/91C0B3B7-2102-49AE-9647-61904A9DB030/tmp/com.vassar.bluis-Inbox/A Sample PDF.pdf' (OS Error: No such file or directory, errno = 2)
#0 _File.length. (dart:io/file_impl.dart:376:9)
#1 _rootRunUnary (dart:async/zone.dart:1134:38)
#2 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
#3 _FutureListener.handleValue (dart:async/future_impl.dart:139:18)
#4 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:680:45)
#5 Future._propagateToListeners (dart:async/future_impl.dart:709:32)
#6 Future._completeWithValue (dart:async/future_impl.dart:524:5)
#7 Future._asyncComplete. (dart:async/future_impl.dart:554:7)
#8 _rootRun (dart:async/zone.dart:1126:13)
#9 _CustomZone.run (dart:async/zone.dart:1023:19)
#10 _CustomZone.runGuarded (dart:async/zone.dart:925:7)
#11 _CustomZone.bindCallbackGuarded. (dart:async/zone.dart:965:23)
#12 _microtaskLoop (dart:async/schedule_microtask.dart:43:21)
#13 _startMicrotaskLoop (dart:async/schedule_microtask.dart:52:5)

@miguelpruivo
Copy link
Owner

@shahnawazahmed88 can you post your code where you call the picker? It looks like you are creating a File instance with a wrong path.

@shahnawazahmed88
Copy link
Author

void onFileUploadIconClick(String datatype) async {
// File Upload Clicked
String filePath;
/** Can upload image, video, audio, pdf and any other file format in the
* default file finder **/
switch (datatype) {
case "image":
filePath = await FilePicker.getFilePath(
type: FileType.image,
);
break;
case "video":
filePath = await FilePicker.getFilePath(
type: FileType.video,
allowedExtensions: ['mp4'],
);
break;
case "audio":
filePath = await FilePicker.getFilePath(
type: FileType.audio,
allowedExtensions: ['mp3'],
);
break;
case "pdf":
filePath = await FilePicker.getFilePath(
type: FileType.custom,
allowedExtensions: ['pdf'],
);
break;
default:
filePath = await FilePicker.getFilePath(
type: FileType.any,
);
}

if (filePath != null && filePath.isNotEmpty) {
  // Valid file path returned
  // Get file name from the path
  File file = new File(filePath);
  String filename = basename(file.path);

// print("XXXXXXXXXXXXXXXXXXXXXXXXXXX -- File name --" + filename);

  // Generate UUID, use as new filename
  String newFileName = new Uuid().v1();

// print("XXXXXXXXXXXXXXXXXXXXXXXXXXX -- New Name -- $newFileName");

  // Add value to user entered fields map for the form
  formMap.addKeyToFormFieldSubmissionValue(widget.id, CommonConstants.SUBMISSION_OBJECT_VAL, newFileName);

  // Save entry to DB for media sync
  _addFileEntryToMediaTable(filename, newFileName, filePath, "pdf");
  print("filename$filename $newFileName $filePath")
  if (formMap.cameraUuids != null) {
    formMap.cameraUuids.add(newFileName.toString());
  } else {
    formMap.cameraUuids = List();
    formMap.cameraUuids.add(newFileName.toString());
  }
  // Set state to refresh icon
  setState(() {
    iconData = Icons.check;
  });
} else {
  // TODO : Log error
  Toast.show(CommonConstants.NO_FILE_FOUND, context);
}

}

@miguelpruivo
Copy link
Owner

Add a statement after the switch case and if that prints, it’s nothing related to the picker but with something you’re doing afterwards.

By looking at your first log, I can see that you have a valid file path, hence, it should be ok. Wrap all of that code with a try-catch clause and print both the error and stack trace. You’ll find where it comes from.

@miguelpruivo
Copy link
Owner

@shahnawazahmed88 have you managed to solve it?

@shahnawazahmed88
Copy link
Author

@miguelpruivo here is my complete code, and its working pretty fine with Android devices

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart';
import 'package:toast/toast.dart';
import 'package:uuid/uuid.dart';
import 'dart:io';

import '../../../db/models/form_media_table.dart';
import '../../../models/app_meta_data_config.dart';
import '../../../ua_app_context.dart';
import '../../../ui/helpers/form_values.dart';
import '../../../ui/themes/color_theme.dart';
import '../../../ui/themes/text_theme.dart';
import '../../../ui/themes/uniapp_css.dart';
import '../../../ui/widgets/formelements/form_transaction_info.dart';
import '../../../utils/common_constants.dart';
import '../../../utils/media_action_type.dart';
import '../../../utils/media_subtype.dart';
import '../../../utils/media_type.dart';
import '../../../utils/media_upload_status.dart';
import '../../../utils/string_utils.dart';

class FormFileUpload extends StatefulWidget {
  final String id;
  final String title;
  final String datatype;
  final String appId;
  final String projectId;
  final String externalProjectId;
  final String uiType;
  final bool showInfo;
  final bool isBorderRequired;

  FormFileUpload({
    this.id,
    this.title,
    this.datatype,
    this.appId,
    this.projectId,
    this.externalProjectId,
    this.uiType,
    this.showInfo,
    this.isBorderRequired,
  });

  @override
  _FileUploadScreenState createState() {
    return _FileUploadScreenState();
  }
}

class _FileUploadScreenState extends State<FormFileUpload> {
  bool _isBorderRequired;
  BuildContext context;
  IconData iconData = Icons.file_upload;

  @override
  void initState() {
    super.initState();
    _isBorderRequired = widget.isBorderRequired;
  }

  @override
  Widget build(BuildContext context) {
    this.context = context;
    if (_isBorderRequired == null) {
      _isBorderRequired = true;
    }
    return Padding(
      padding: _isBorderRequired
          ? UniappCSS.smallHorizontalPadding
          : UniappCSS.largeHorizontalPadding,
      child: Container(
        decoration: BoxDecoration(
          borderRadius: UniappCSS.widgetBorderRadius,
          border: UniappCSS.widgetBorder,
          color: UniappColorTheme.fillColor,
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Row(
              mainAxisSize: MainAxisSize.max,
              children: <Widget>[
                Expanded(
                  child: Container(
                    padding: UniappCSS.smallHorizontalAndVerticalPadding,
                    child: Text(
                      StringUtils.getTranslatedString(widget.title),
                      style: UniappTextTheme.defaultWidgetStyle,
                    ),
                  ),
                ),
                IconButton(
                  icon: Icon(iconData),
                  iconSize: UniappCSS.largeIconSize,
                  tooltip: "File Upload",
                  color: UniappColorTheme.widgetColor,
                  onPressed: () => onFileUploadIconClick(widget.datatype),
                ),
                TransactionInfoWidget(
                  formFieldKey: widget.id,
                  showInfo: widget.showInfo,
                  formFieldUiType: widget.uiType,
                ),
                SizedBox(
                  width: 8.0,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  void onFileUploadIconClick(String datatype) async {
    // File Upload Clicked
    String filePath;
    /** Can upload image, video, audio, pdf and any other file format in the
     * default file finder **/
    switch (datatype) {
      case "image":
        filePath = await FilePicker.getFilePath(
          type: FileType.image,
        );
        break;
      case "video":
        filePath = await FilePicker.getFilePath(
          type: FileType.video,
          allowedExtensions: ['mp4'],
        );
        break;
      case "audio":
        filePath = await FilePicker.getFilePath(
          type: FileType.audio,
          allowedExtensions: ['mp3'],
        );
        break;
      case "pdf":
        filePath = await FilePicker.getFilePath(
          type: FileType.custom,
          allowedExtensions: ['pdf'],
        );
        break;
      default:
        filePath = await FilePicker.getFilePath(
          type: FileType.any,
        );
    }

    if (filePath != null && filePath.isNotEmpty) {
      // Valid file path returned
      // Get file name from the path
      File file = new File(filePath);
      String filename = basename(file.path);
//      print("XXXXXXXXXXXXXXXXXXXXXXXXXXX -- File name --" + filename);

      // Generate UUID, use as new filename
      String newFileName = new Uuid().v1();
//      print("XXXXXXXXXXXXXXXXXXXXXXXXXXX -- New Name -- $newFileName");

      // Add value to user entered fields map for the form
      formMap.addKeyToFormFieldSubmissionValue(widget.id, CommonConstants.SUBMISSION_OBJECT_VAL, newFileName);

      // Save entry to DB for media sync
      _addFileEntryToMediaTable(filename, newFileName, filePath, "pdf");
      if (formMap.cameraUuids != null) {
        formMap.cameraUuids.add(newFileName.toString());
      } else {
        formMap.cameraUuids = List();
        formMap.cameraUuids.add(newFileName.toString());
      }
      // Set state to refresh icon
      setState(() {
        iconData = Icons.check;
      });
    } else {
      // TODO : Log error
      Toast.show(CommonConstants.NO_FILE_FOUND, context);
    }
  }

  _addFileEntryToMediaTable(String fileName, String newFileName,
      String filePath, String fileExtension) async {
    AppMetaDataConfig appMetaConfig = UAAppContext.getInstance().appMDConfig;
    int retries = CommonConstants.MEDIA_IMAGE_DEFAULT_RETRIES;

    if (appMetaConfig != null &&
        appMetaConfig.mediaretries != null &&
        appMetaConfig.mediaretries != 0) {
      retries = appMetaConfig.mediaretries;
    }

    // Adding filename and externalProjectId to additional properties map
    Map<String, String> additionalProperties = new Map();
    additionalProperties[CommonConstants.EXTERNAL_PROJECT_ID] =
        widget.externalProjectId;
    additionalProperties["fileName"] = fileName;

    FormMediaTable formMedia = new FormMediaTable(
      widget.appId,
      UAAppContext.getInstance().userID,
      newFileName,
      0,
      widget.projectId,
      filePath,
      null,
      false,
      CommonConstants.DEFAULT_LATITUDE,
      CommonConstants.DEFAULT_LONGITUDE,
      CommonConstants.DEFAULT_ACCURACY,
      CommonConstants.DEFAULT_BEARING,
      MediaTypeHelper.getValue(MediaType.PDF),
      MediaSubTypeHelper.getValue(MediaSubType.FULL),
      fileExtension,
      0,
      0,
      MediaActionTypeHelper.getValue(MediaActionType.UPLOAD),
      retries,
      MediaUploadStatusHelper.getValue(MediaUploadStatus.NEW),
      additionalProperties,
    );

    await UAAppContext.getInstance()
        .unifiedAppDBHelper
        .insertFormMedia(formMedia);
  }
}

@miguelpruivo
Copy link
Owner

Does that happen with another file?

@shahnawazahmed88
Copy link
Author

No, I am using Video, and Photo all are working well, except document, but this is also working well in android device, only occurring issue in iOS 13.4 (I am using this one).

@miguelpruivo
Copy link
Owner

Sure. But what if you pick a different document on iOS? Could you try it? Does that still happen? Are you on latest Xcode version? I can’t see anything wrong with the code itself, to me looks like it just can’t open a descriptor for that file (probably due to the name or any other particular reason).

@miguelpruivo
Copy link
Owner

Any news on this?

@shahnawazahmed88
Copy link
Author

@miguelpruivo hey bro, everything is done from my side, just one thing I want to try, I want to run my code in lower version of the iOS device, currently I am using iOS 13.4, how it could be? might be this issue with some version-specific?

@vanshg395
Copy link

I am facing same issue on ios

@shahnawazahmed88
Copy link
Author

@vanshg395 Hey bro, which iOS version currently you are using now?

@vanshg395
Copy link

vanshg395 commented May 11, 2020

Ios 13.4, the problem is only occurring with pdf files and that too randomly, sometimes it works, sometimes it doesn’t.

@shahnawazahmed88
Copy link
Author

Its a sumilator or real device?

@vanshg395
Copy link

vanshg395 commented May 11, 2020 via email

@shahnawazahmed88
Copy link
Author

Exactly sometimes is working and sometimes it not, so except pdf file is it working for other documents fine? did you test with the lower version of the iOS device?

@vanshg395
Copy link

vanshg395 commented May 11, 2020 via email

@shahnawazahmed88
Copy link
Author

For me the same code working nicely in android devices, Bro, let me know if you find any solution for it

@miguelpruivo
Copy link
Owner

Does that happen to work randomly for the same file? Or different files?

@vanshg395
Copy link

vanshg395 commented May 11, 2020 via email

@miguelpruivo
Copy link
Owner

That’s odd as far as it concerns to picking files from the picker. It only gives you the path and that’s it. It didn’t even tries to open the file. Is it always a pdf? Does that happen with any other type? Could you tell me the name of the file so I can try to replicate it here?

@vanshg395
Copy link

vanshg395 commented May 11, 2020 via email

@miguelpruivo
Copy link
Owner

@vanshg395 can you tell me exactly the name of the file that you are picking? So I can create a file with the same name to replicate it? It will be hard to fix if I cannot reproduce it.

@vanshg395
Copy link

vanshg395 commented May 11, 2020 via email

@miguelpruivo
Copy link
Owner

Have you managed to solve it @vanshg395?

@miguelpruivo
Copy link
Owner

Closing due to inactivity. Feel free to reopen it if you still experience the same issue on latest versions (plugin and Flutter @ stable channel).

Thank you.

@bergtorresn
Copy link

This problem occurs when I select the file and wait some time before making the request to send to the server, when sending capture this error. If I don't wait a while, the problem does not occur.

Here my code:

    try {
      _bloc.path = await FilePicker.getFilePath(
          type: FileType.custom,
          allowedExtensions: ['pdf', 'png', 'jpg', 'jpeg']);

 if (_bloc.path != null && _bloc.path.isNotEmpty) {
      _navigateToAnotherScreen(AnotherScreen(path:_bloc.path));
    }
    } on PlatformException catch (e) {
     // error
    }

On another screen, I just show the content and there is a button to send to the server.

in the button method.

MultipartFile multiPartFile = await MultipartFile.fromFile(_filePath,
           filename: _filePath.split("/").last);

.. create a formData and send it to server.

@miguelpruivo
Copy link
Owner

@bergtorresn iOS or Android?

@bergtorresn
Copy link

@miguelpruivo only iOS

@miguelpruivo
Copy link
Owner

@bergtorresn yes this is working as expected. Files on iOS that are on tmp directory are only cached briefly and system can actually purge them during app instance (which is odd I know). If you don’t plan to use the file for a while before uploading it, you may want to cache it on your send (it can be done easily).

@bergtorresn
Copy link

Do you suggest creating this file locally and using it to upload to the server and delete it?

@miguelpruivo
Copy link
Owner

@bergtorresn copying to your app’s temporary folder (cache). You don’t need to delete it explicitly afterwards. The system will purge whenever it needs it.

@iury0393
Copy link

@miguelpruivo i am trying to cache it the file but without success, how can i do it instead of using the tmp folder? (That is the pattern).

@miguelpruivo
Copy link
Owner

Using the path provider plugin to get access to documents directory and then making a copy of the file into it or just moving it to there right after picking.

@b1acKr0se
Copy link

For anyone looking for the code:

import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';

File file = File(result.files.single.path);
if (Platform.isIOS) {
  final documentPath = (await getApplicationDocumentsDirectory()).path;
  file = await file.copy('$documentPath/${path.basename(file.path)}');
}
return file;

@brendansiow
Copy link

Hi, shall we delete the file after we proceed to upload the file to server using @b1acKr0se caching way?

@b1acKr0se
Copy link

@walaoehh If you don't want to care about the file afterwards, you can consider using getTemporaryDirectory() instead of getApplicationDocumentsDirectory(). It seems the system will purge files in this directory at any time, so proceed with caution. If you use getApplicationDocumentsDirectory() it's your responsibility to remove the file after you're done with it.

@SerdarYildiz06
Copy link

I am trying to post local phone asset but I am taking "FileSystemException (FileSystemException: Cannot retrieve length of file, path = 'cache/file_picker/IMG_20220428_115542.jpg' (OS Error: Permission denied, errno = 13))". This error. What is the main problem?

@voratham
Copy link

voratham commented Mar 22, 2023

For anyone looking for the code:

import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';

File file = File(result.files.single.path);
if (Platform.isIOS) {
  final documentPath = (await getApplicationDocumentsDirectory()).path;
  file = await file.copy('$documentPath/${path.basename(file.path)}');
}
return file;

👏 🎉 It'work for me
i have using on flutter 3.3.0 version with IOS 15.7.3 real-device and library file_picker = 5.2.5

@omarmgerbie
Copy link
Contributor

guys can you check this answer its describing the issue and a good workaround for it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
triage Further information is requested
Projects
None yet
Development

No branches or pull requests

10 participants