Giter Club home page Giter Club logo

dartftp's People

Contributors

chaseguru avatar salim-lachdhaf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

dartftp's Issues

Unable to list files on the FTP server ... Getting the following error

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: RangeError (end): Invalid value: Only valid value is 0: -1
E/flutter (30359): #0 RangeError.checkValidRange (dart:core/errors.dart:379:9)
E/flutter (30359): #1 _StringBase.substring (dart:core-patch/string_patch.dart:398:27)
E/flutter (30359): #2 TransferUtil.parsePortPASV
transfer_util.dart:26
E/flutter (30359): #3 TransferUtil.parsePort
transfer_util.dart:5
E/flutter (30359): #4 FTPDirectory.listDirectoryContent

Downloading file using FTPES causes Deadlock

Code is working fine when using SecurityType.FTP. But when switching over to SecurityType.FTPES the applications gets stuck at Start downloading...

There is an error in the log which states that the size is not allowed in ascii mode:
[code= 550, message= 550 SIZE not allowed in ASCII mode]

After that it will be switched to TYPE A and the size is returned.

But on opening the DataSocket the code seems to try again in ASCII which might be part of the failure?
I tried to switch to TYPE A, but it had no effect.:
await ftpConnect.sendCustomCommand("TYPE A");

WinSCP is opening binary mode for the data connection which is working.

I tried setting the transfer type manully to await ftpConnect.setTransferType(TransferType.binary);
But it gets stuck on the same position. So it might has to do with the SSL handshake?

@salim-lachdhaf, thank you for your effort implementing this plugin! Do you have a clue why this fails? Is there a way to force binary download instead of ASCII Mode? Thank you!

Log from WinSCP using FTPES successfull:

> 2023-08-25 11:14:39.912 RETR xxxxxx.txt
. 2023-08-25 11:14:39.912 Verbindung mit 13.37.150.67:50069 wird hergestellt …
< 2023-08-25 11:14:39.991 150 Opening BINARY mode data connection for xxxxxx.txt (2091 bytes)
. 2023-08-25 11:14:40.032 Session ID reused
. 2023-08-25 11:14:40.032 Using TLSv1.2, cipher TLSv1.2: ECDHE-RSA-AES128-GCM-SHA256, 2048 bit RSA, ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH     Au=RSA  Enc=AESGCM(128) Mac=AEAD
. 2023-08-25 11:14:40.032 TLS-Verbindung hergestellt
. 2023-08-25 11:14:40.112 Preserving timestamp [2023-08-25T08:21:37.000Z]
< 2023-08-25 11:14:40.114 226 Transfer complete
. 2023-08-25 11:14:40.114 Herunterladen erfolgreich
. 2023-08-25 11:14:40.114 Transfer done: '/results/xxxxxx.txt' => 'C:\Users\thoma\Documents\test\xxxxxx.txt.txt' [2091]

Log from flutter:

flutter: [2023-08-25 10:54:31.286524] Connecting...
flutter: [2023-08-25 10:54:31.383074] Connection established, waiting for welcome message...
flutter: [2023-08-25 10:54:31.688468] < FTPReply =  [code= 220, message= 220 FTP on abc1337.kasserver.com ready]
flutter: [2023-08-25 10:54:31.688468] > AUTH TLS
flutter: [2023-08-25 10:54:31.992547] < FTPReply =  [code= 234, message= 234 AUTH TLS successful]
flutter: [2023-08-25 10:54:32.117675] > PBSZ 0
flutter: [2023-08-25 10:54:32.420489] < FTPReply =  [code= 200, message= 200 PBSZ 0 successful]
flutter: [2023-08-25 10:54:32.420489] > PROT P
flutter: [2023-08-25 10:54:32.720492] < FTPReply =  [code= 200, message= 200 Protection set to Private]
flutter: [2023-08-25 10:54:32.721451] > USER xxyy
flutter: [2023-08-25 10:54:33.022062] < FTPReply =  [code= 331, message= 331 Password required for xxyy]
flutter: [2023-08-25 10:54:33.022062] > PASS yyxx
flutter: [2023-08-25 10:54:33.322899] < FTPReply =  [code= 230, message= 230 User xxyy logged in]
flutter: [2023-08-25 10:54:33.322899] Connected!
flutter: [2023-08-25 10:54:33.325508] Download settings.json to C:\Users\thoma\AppData\Roaming\app\settings\settings.json
flutter: [2023-08-25 10:54:33.326509] > SIZE settings.json
flutter: [2023-08-25 10:54:33.627328] < FTPReply =  [code= 550, message= 550 SIZE not allowed in ASCII mode]
flutter: [2023-08-25 10:54:33.627328] > TYPE I
flutter: [2023-08-25 10:54:33.927898] < FTPReply =  [code= 200, message= 200 Type set to I]
flutter: [2023-08-25 10:54:33.927898] > SIZE settings.json
flutter: [2023-08-25 10:54:34.229085] < FTPReply =  [code= 213, message= 213 2397]
flutter: [2023-08-25 10:54:34.229085] > TYPE A
flutter: [2023-08-25 10:54:34.532745] < FTPReply =  [code= 200, message= 200 Type set to A]
flutter: [2023-08-25 10:54:34.532745] > PASV
flutter: [2023-08-25 10:54:34.833702] < FTPReply =  [code= 227, message= 227 Entering Passive Mode (85,13,150,67,195,189).]
flutter: [2023-08-25 10:54:34.834671] > RETR settings.json
flutter: [2023-08-25 10:54:34.834671] Opening DataSocket to Port 50109
flutter: [2023-08-25 10:54:35.185803] < FTPReply =  [code= 150, message= 150 Opening ASCII mode data connection for settings.json (2397 bytes)]
flutter: [2023-08-25 10:54:35.185803] Start downloading...

checkFolderExistence ftpconnect

/flutter (12196): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: LateInitializationError: Field '_socket@1399506163' has not been initialized.
E/flutter (12196): #0 FTPSocket._socket (package:ftpconnect/src/ftp_socket.dart)
ftp_socket.dart:1
E/flutter (12196): #1 FTPSocket.sendCommand
ftp_socket.dart:76
E/flutter (12196): #2 FTPDirectory.changeDirectory
directory.dart:30
E/flutter (12196): #3 FTPConnect.changeDirectory
ftpconnect_base.dart:139
E/flutter (12196): #4 FTPConnect.checkFolderExistence
ftpconnect_base.dart:273
E/flutter (12196): #5 FTPConnect.createFolderIfNotExist
ftpconnect_base.dart:281

'_socket@1665506163' has not been initialized.

I have this error when trying to use this package at version 2.0.2:

[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: LateInitializationError: Field '_socket@1665506163' has not been initialized.

And it point to this file and line: ftp_socket.dart:195

I'm testing it on an iPhone S.

On release mode do not working

When I Obfuscate the code the plugin not found my server FTP...
but when I do in debug mode It's working...

do you have proguard?

listDirectoryContent (OnlyNames) (Response: 500 'MLSD': command not understood))

with the listDirectoryContentOnlyNames() & listDirectoryContent() method I am getting the following exception:

FTPConnectException (FTPConnectException: Connection refused. (Response: 500 'MLSD': command not understood))

OS: Linux Fedora 40

other methods like checkFolderExistence() are working fine

example code:

import 'package:ftpconnect/ftpconnect.dart';

main() async {
  FTPConnect ftpConnect = FTPConnect('example.com', user: 'user', pass: 'pass');
  
  await ftpConnect.connect();
  
  List<String> DirectoryContent = await ftpConnect.listDirectoryContentOnlyNames();

  print('DirectoryContent: $DirectoryContent');

  await ftpConnect.disconnect();
}

FTPS Not working?

Filezilla is able to connect to a machine, and I got curl working too, but I can't get connect in the library to work.

final ftp = FTPConnect(
  '10.22.3.185',
  port: 990,
  user: 'asdf',
  pass: 'asdfasdf',
  securityType: SecurityType.FTPS,
  timeout: 3,
);
await ftp.connect();

Depending on combination of settings it times out or gets a connection refused.

I didn't see a FTPS example in the lib/example folder either. It does seem like your code attempts to do stuff for FTPS, and it's possible I'm configuring something wrong.

Facing error socketException: Connection reset by peer (OS Error: Connection reset by peer, errno = 54) on ios

Hi
I am facing the above error when uploading multiple files 4to 5 files on ios emulator iphone 14 pro ios v 16.4.
Below is the code
for (int i = 0; i < file.length; i++) {

        // await ftpConnect.connect();

Future.delayed(Duration(seconds: 2),(){
log("delay started");
});
log("delay ended");

        currentIndex = i;
        if (cancelUpload.value == false && isUploadSucess.value == false) {
          log("lenfth of file" + file.length.toString());
          log("current file path:" + file[i].path);
          File files = File(file[i].path);
          log("current file path ---->> :" + files.path);
          log("current file paths before uploading :" +
              tabController1.file.toString());

          await ftpConnect.uploadFile(
            File(file[i].path),
            supportIPV6: false,
          );
          double data1 = fileCount.value.toDouble();
          showFileCount.value = data1.toString();
          //increase the value of file by one when the file is uploaded sucessfully
          //below code is to calculate upload percent
          log("file count" + fileCount.value.toString());
          showUploadPercentage.value = uploadPercent.value;
          //uploading xml file
          String fileName = p.basename(file[i].path).split('.').first;
          // remove extension from file name
          // fileName = fileName.substring(0, fileName.lastIndexOf('.'));
          //faster way

          final myxmlFile = File('$_dirPath/${fileName}.xml');
          log("XML FILE NAME >>>> ${myxmlFile.path}");
          await myxmlFile.writeAsString(document.toXmlString(pretty: true));
          await ftpConnect.uploadFile(myxmlFile);
          fileCount.value++;
          uploadPercent.value =
              (fileCount.value.toDouble() / totalcount) * 100;
          double data = fileCount.value.toDouble();
          showFileCount.value = data.toString();
          log("file count" + fileCount.value.toString());
          log("totalFileCount" + totalFileCount.value.toString());
          log("upload percent" + uploadPercent.value.toString());
          log("above sucess" + uploadPercent.value.toString());
          showUploadPercentage.value = uploadPercent.value;
          // await ftpConnect.disconnect();
          if (showUploadPercentage.value == 100.0) {
            Wakelock.disable();
            isUploadSucess.value = true;
            Fluttertoast.showToast(
                msg: "Successfully Uploaded".tr,
                gravity: ToastGravity.CENTER);

            log("upload was" + isUploadSucess.toString());
          }
        } else if (cancelUpload.value == true) {
          Fluttertoast.showToast(
              msg: "Upload was canceled", gravity: ToastGravity.CENTER);
        }
      }

Sometimes stuck at `Start downloading...`

Sometimes, when i want to download a jpeg file, the library print Start downloading... and wait indefinitly.

i am already in binary mode.

i think there is a time desync with the socket opening or something like that because it seems that the socket is listening and nothing is answered.

it does block there lib/src/commands/file.dart:94.

We use a Pure-FTPd as server.

I/flutter (29447): [2024-05-17 16:59:18.494143] Download /80/STM6001_DIA_001/SITE80_STM6001_DIA_001_2023-3-30T9_59_31.jpeg to /data/user/0/<APP ID PURPOSELY HIDDEN>/app_flutter/ftpfiles/SITE80_STM6001_DIA_001_2023-3-30T9_59_31.jpeg
I/flutter (29447): [2024-05-17 16:59:18.495056] > SIZE /80/STM6001_DIA_001/SITE80_STM6001_DIA_001_2023-3-30T9_59_31.jpeg
I/flutter (29447): [2024-05-17 16:59:18.800862] < FTPReply =  [code= 213, message= 213 135512]
I/flutter (29447): [2024-05-17 16:59:18.802551] > EPSV
I/flutter (29447): [2024-05-17 16:59:19.110779] < FTPReply =  [code= 229, message= 229 Extended Passive mode OK (|||40092|)]
I/flutter (29447): [2024-05-17 16:59:19.111523] > RETR /80/STM6001_DIA_001/SITE80_STM6001_DIA_001_2023-3-30T9_59_31.jpeg
I/flutter (29447): [2024-05-17 16:59:19.112454] Opening DataSocket to Port 40092
I/flutter (29447): [2024-05-17 16:59:19.442433] < FTPReply =  [code= 226, message= 150-Accepted data connection
I/flutter (29447): 150 132.3 kbytes to download
I/flutter (29447): 226-File successfully transferred
I/flutter (29447): 226 0.000 seconds (measured here), 282.76 Mbytes per second]
I/flutter (29447): [2024-05-17 16:59:19.445156] Start downloading...

Error in connection with FTPS help me

I'm trying to make a FTPS connection but it did't work
my code:

FTPConnect ftpConnect = FTPConnect('devftp.made.net', user: AccountManager.instance.agente!.companyConfiguration!.usernameFTP, pass: AccountManager.instance.agente!.companyConfiguration!.passwordFTP, showLog: kDebugMode, port: 21, securityType: SecurityType.FTPS); await ftpConnect.connect();

here is the log:

flutter: [2023-12-06 15:19:25.576751] Connecting... flutter: [2023-12-06 15:19:25.613803] Connection established, waiting for welcome message... flutter: [2023-12-06 15:19:25.918900] < FTPReply = [code= 220, message= 220 Welcome on Made in App FTP server. Shaken, not stirred.] [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: HandshakeException: Handshake error in client (OS Error: WRONG_VERSION_NUMBER(tls_record.cc:231)) #0 _SecureFilterImpl._handshake (dart:io-patch/secure_socket_patch.dart:99:46) #1 _SecureFilterImpl.handshake (dart:io-patch/secure_socket_patch.dart:143:25) #2 _RawSecureSocket._secureHandshake (dart:io/secure_socket.dart:920:54) #3 _RawSecureSocket._tryFilter (dart:io/secure_socket.dart:1049:19) <asynchronous suspension>

helpme Error uploading file to FTP server: FTPConnectException: Connection refused.

I need help..

I/flutter (16531): Error al subir el archivo al servidor FTP: FTPConnectException: Connection refused. (Response: 150 Opening data channel for file upload to server of "/archivo_2023-07-04_20-12-46.txt"
I/flutter (16531): 550 Could not open file for writing.)

//I try to upload a file.txt I have the correct credentials too, I have a connection to the ftp server and also the permissions to write, read on the server. But I get the error mentioned previously.

//code in android studio:

Future<File> _createFile() async {
    final now = DateTime.now();
    final formatter = DateFormat('yyyy-MM-dd_HH-mm-ss');
    final fileName = 'archivo_${formatter.format(now)}.txt';
    final file = await _localFile(fileName);
    if (!file.existsSync()) {
      file.createSync(recursive: true);
    }
    return file;
  }

Future<void> _uploadFileToFTP(File fileToUpload) async {
  FTPConnect ftpConnect = FTPConnect('000.000.0.000', user: 'Rrrrrrr', pass: '333333');

  try {
    await ftpConnect.connect();
    await ftpConnect.uploadFileWithRetry(fileToUpload, pRetryCount: 2);
  } catch (e) {
    print('Error al subir el archivo al servidor FTP: $e');
  } finally {
    await ftpConnect.disconnect();
  }
}

void _guardarDatos() async {
  if (_formKey.currentState!.validate()) {
    final codigoInterno = _codigoInternoController.text;
    final kilometraje = _kilometrajeController.text;
    final observaciones = _observacionesController.text;

    final file = await _createFile();
    final sink = file.openWrite(mode: FileMode.append);
    sink.write('Código Interno: $codigoInterno\n');
    sink.write('Kilometraje u Horómetro: $kilometraje\n');
    sink.write('Observaciones: $observaciones\n');
    sink.write('\n');
    await sink.flush();
    await sink.close();

    await _uploadFileToFTP(file);

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('Datos guardados correctamente.')),
    );
  }
}

downloadFile With Retry method hangs

Thank you for your package.

According to your documentation, everything from connecting to ftp, downloading, and disconnecting worked perfectly.

However, sometimes the ftp server is connected, but the download stops. When I took a log one by one, it was confirmed that it stopped at FileDownload(_socket, mode, _log).downloadFile(context, sRemoteName, fFile, onProgress: onProgress, supportIPV6: supportIPv6);.

exactly

await dataSocket.listen((data) {
      sink.add(data);
      if (onProgress != null) {
        received += data.length;
        var percent = ((received / fileSize) * 100).toStringAsFixed(2);
        //in case that the file size is 0, then pass directly 100
        double percentVal = double.tryParse(percent) ?? 100;
        if (percentVal.isInfinite || percentVal.isNaN) percentVal = 100;
        onProgress(percentVal, received, fileSize);
      }
    }).asFuture();

The inside of listen is processed, but it seems that an error occurs in asFuture(). Is there any way to handle the exception??

FTPEntryType not exported

FTPEntryType is not exported, so it is not possible to distinguish between files and folders using FTPEntry.type.

Dirty workaround: Using the auto-assigned index of the enum:

enum FTPEntryType {
  FILE, // 0
  DIR, // 1
  LINK, // 2
  UNKNOWN // 3
}

Eg:

final entries = ftp.listDirectoryContent();

entries.forEach((entry) {
  if (entry.type.index == 0) {
    // Entry is file
  }
  else if (entry.type.index == 1) {
    // Entry is directory
  }
  ...
}

Can't upload a binary file

Hello people, does anyone have the same problem than me? I cant upload a binary file like .jpg always i tried the file is corrupted in ftp server.

Unexpected conversion of spaces in binary file ( Wav type)

Hey there, Flutter enthusiasts!

I'm new to learning Flutter, so please bear with me if you come across any silly mistakes in the code. The problem I'm currently dealing with is related to handling binary files, specifically wav files. The sample code for text files is working like a charm - I can connect to FTP, download, and upload files without any issues. However, when it comes to downloading wav files, the resulted audio sounds distorted.

Upon further investigation, I discovered that the spaces (0x20) in the original file on the FTP server (named message2.wav) were being converted to 0x0D in the downloaded version (let's call it DownloadedStepByStep.wav).

1
2

I have shared the files for reference, but unfortunately, I couldn't upload them here. Thanks for your understanding!

Here is the full source code which is slightly changed (the FTP credentials removed):

__import 'dart:ffi';
import 'dart:io';
import 'dart:typed_data';
import 'package:ftpconnect/ftpconnect.dart';
import 'dart:convert' show Encoding, LineSplitter, Utf8Codec, Utf8Decoder, Utf8Encoder, utf8;

void main() async {
final FTPConnect _ftpConnect = new FTPConnect( "ftp.xxxxxx.com", user: "[email protected]", pass: "xxxxx", showLog: true , port: 21 );

///an auxiliary function that manage showed log to UI
Future _log(String log) async {
print(log);
await Future.delayed(Duration(seconds: 1));
}

///mock a file for the demonstration example
const  X=<int>[];   // added by me as input of List<int> to function below

Future _fileMockwav({fileName = 'FlutterTest.wav' , content =X }) async {
final Directory directory = Directory('/test')..createSync(recursive: true);
final File file = File('${directory.path}/$fileName');
await file.writeAsBytes(content ); // changed by me

return file;

}

Future _downloadStepByStep() async {
try {
await _log('Connecting to FTP ...');

  await _ftpConnect.connect();

  await _log('Downloading ...');
  String fileName = '../message2.wav';

  //here we just prepare a file as a path for the downloaded file
  File downloadedFile = await _fileMockwav(fileName: 'DownloadedStepByStep.wav');
  await _ftpConnect.downloadFile(fileName, downloadedFile);
  await _log('file downloaded path: ${downloadedFile.path}');
  await _ftpConnect.disconnect();
} catch (e) {
  await _log('Downloading FAILED: ${e.toString()}');
}

}

await downloadStepByStep();
}
_

Accented letters

Hi,

I work with french accented letters in the filenames but when I use listDirectoryContent(), I have some encoding problems knowing that those files are correctly named on the remote server

IE :

"I/flutter (23193): Accusé de réception.pdf" instead of "Accusé de réception.pdf"

Is there a missing parameter or something I omitted to have properly formatted filenames ?

Thanks in advance

Regards,
Pierre

setTransferType binary is not working at all

When I use the setTransferType(TransferType.binary);, the client will throw errors or timeout on nearly every commands. I need to use the binary file transfer as the ascii one is corrupting my jpeg files

Exception: Invalid Image Data

I am downloading image from ftp and saving it into a file but when I ma trying to show it son screen I got this exception

Can anyone help ?

final ftpConnect = FTPConnect(DBConstants.ftpServer,
        user: DBConstants.ftpUser, pass: DBConstants.ftpPassword);

    await ftpConnect.connect();
    await ftpConnect.changeDirectory(DBConstants.publicImgDirPath);

    final appDir = await getApplicationDocumentsDirectory();
    final imgName = studentFilePath.split('images/').last;
    final localFilePath = '${appDir.path}/$imgName';
    final fFile = File(localFilePath);

    try {
      final downloadedFile = await ftpConnect.downloadFile(imgName, fFile);

      LoadingHelper.dismissLoader();
      return fFile;
    } on FTPConnectException catch (e) {
      LoadingHelper.dismissLoader();
      LoadingHelper.showErrorDialog(e.message);
    } finally {
      ftpConnect.disconnect();
    }
    LoadingHelper.dismissLoader();

Copy or Move

Is it possible to move or copy files from one directory to another?

FormatException: Trying to read MMM from May 28 19:50 2023 at 0

When I try to list the directory with:

final ftpConnect = FTPConnect(event.configFtp.address, user: event.configFtp.username, pass: event.configFtp.password, port: 21);
  ftpConnect.listCommand = ListCommand.LIST;
  await ftpConnect.connect();
  await ftpConnect.listDirectoryContentOnlyNames();

I receive the following error:

E/flutter ( 9458): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: FormatException: Trying to read MMM from May 28 19:50 2023 at 0
E/flutter ( 9458): #0      _DateFormatField.throwFormatException (package:intl/src/intl/date_format_field.dart:87:5)
E/flutter ( 9458): #1      _DateFormatPatternField.parseField (package:intl/src/intl/date_format_field.dart:350:7)
E/flutter ( 9458): #2      _DateFormatPatternField.parse (package:intl/src/intl/date_format_field.dart:261:5)
E/flutter ( 9458): #3      DateFormat._parse (package:intl/src/intl/date_format.dart:384:13)
E/flutter ( 9458): #4      DateFormat.parse (package:intl/src/intl/date_format.dart:315:7)
E/flutter ( 9458): #5      new FTPEntry._parseLIST (package:ftpconnect/src/ftp_entry.dart:198:40)
E/flutter ( 9458): #6      new FTPEntry._parseListCommand (package:ftpconnect/src/ftp_entry.dart:150:23)
E/flutter ( 9458): #7      new FTPEntry.parse (package:ftpconnect/src/ftp_entry.dart:56:23)
E/flutter ( 9458): #8      FTPDirectory.directoryContent.<anonymous closure> (package:ftpconnect/src/commands/directory.dart:86:20)
E/flutter ( 9458): #9      List.forEach (dart:core-patch/growable_array.dart:416:8)
E/flutter ( 9458): #10     FTPDirectory.directoryContent (package:ftpconnect/src/commands/directory.dart:83:59)
E/flutter ( 9458): <asynchronous suspension>
E/flutter ( 9458): #11     FTPDirectory.directoryContentNames (package:ftpconnect/src/commands/directory.dart:95:16)
E/flutter ( 9458): <asynchronous suspension>
E/flutter ( 9458): #12     FtpBloc._onFtpConnect (package:remanfredi/presentation/transport/bloc/ftp_bloc.dart:31:21)
E/flutter ( 9458): <asynchronous suspension>
E/flutter ( 9458): #13     Bloc.on.<anonymous closure>.handleEvent (package:bloc/src/bloc.dart:229:13)
E/flutter ( 9458): <asynchronous suspension>
E/flutter ( 9458):

Stop transfer - how to handle

Hello, sorry for my maybe stupid question, but im fighting this all the day ;)
What is the best way to stop current transfer? Im using very large files like 100-300gb and i want to add 'stop' functionality.

await ftpConnect.connect();
bool res = await ftpConnect.downloadFile(
fileName,
File(lista2![currentIndex]),
onProgress: (progressInPercent, totalReceived, fileSize) {
percent = progressInPercent;
received = totalReceived;
total = fileSize;

      status = "DL: ${percent}%";
      if (stop) {
        ftpConnect.sendCustomCommand("QUIT");
        ftpConnect.disconnect();
        downloading = false;
        percent = 0.0;
        done = false;
        stop = false;
        notifyListeners();
      }
      notifyListeners();
    },
  );

Im trying something like this all the day and even when its said Disconnected file is still downloading in bg till i stop the app.
Many thanks for help, greets!

Error while downloading file

i get this error when i try to download file in my device redmi note 9 pro but the same code for downloading file is working for other device realme error is - RangeError (index): Invalid value: Only valid value is 0: -1

logic --
Future downloadFile() async {
await initializeFTP();
showCustomLoadingDialog();

isDownloading = true;
downloadProgress = 0.0;

print("Downloading files...");
List<Map<String, dynamic>> allDeliveryLogs = [];

try {
  print("Connecting to FTP server...");

  // Assuming you have an initialized FTP client stored in the variable ftpConnect
  // ...

  print("Changing directory...");
  await ftpConnect!
      .changeDirectory('/ftp/DeliverEsignService/1472589/A/Import/');

  print("Retrieving directory content...");
  final directoryContent = await ftpConnect!.listDirectoryContent();
  print("FTP Server Response: $directoryContent");

  print("Filtering file names...");
  final fileNames = directoryContent
      .where((entry) => entry.name.toLowerCase().endsWith('.db'))
      .map((entry) => entry.name)
      .toList();

  print('File names found: $fileNames');
  if (fileNames.isEmpty) {
    print('No files found for download.');
  }

  // Download and store each file locally
  for (int i = 0; i < fileNames.length; i++) {
    String fileName = fileNames[i];
    print('Processing file $i: $fileName');

    String serverFilePath =
        '/ftp/DeliverEsignService/1472589/A/Import/$fileName';

    // Get the local app directory path using path_provider
    Directory appDir = await getApplicationDocumentsDirectory();
    String localFilePath = '${appDir.path}/$fileName';
    File localFile = File(localFilePath);

    print('Downloading file: $fileName');

    try {
      await ftpConnect?.downloadFileWithRetry(
        serverFilePath,
        localFile,
        onProgress: (progress, received, total) {
          print('Download progress: $progress ($received / $total)');

          downloadProgress = progress;
        },
      );

      print('File downloaded successfully: $fileName');

      // Open the database
      Database database = await openDatabase(localFilePath);

      // Print the schema of the 'deliveryLog' table
      List<Map<String, dynamic>> columns =
          await database.rawQuery("PRAGMA table_info('deliveryLog')");
      print('Table Schema: $columns');

      // Retrieve the data from the SQLite database
      List<Map<String, dynamic>> deliveryLogsData =
          await database.rawQuery('SELECT * FROM deliveryLog');
      print('deliveryLogs: $deliveryLogsData');

      // Create a List of DeliveryLog objects from the database data
      List<DeliveryLog> deliveryLogs = deliveryLogsData
          .map((data) => DeliveryLog(
                recordId: data['recordId'],
                patientID: data['PatientID'],
                nursingHomeID: data['NurshingHomeID'],
                rxID: data['RxID'],
                driverID: data['DriverID'],
                rxNumber: data['RxNumber'],
                fillDate: data['Fill_Date'],
                patientName: data['Patient_Name'],
                address: data['Address'],
                nursingHomeName: data['Nursing_Home_Name'],
                drug: data['Drug'],
                status: data['Status'],
                recipient: data['Recipient'],
                sign: data['Sign'],
                deliveredDateTime: data['Delivered_Date_Time'],
                amount:
                    data['Amount'], // Convert to double if it's not null
                paymentType: data['PaymentType'],
                paymentAmount: data[
                    'PaymentAmount'], // Convert to double if it's not null
              ))
          .toList();

      // Convert List<DeliveryLog> to List<Map<String, dynamic>>
      List<Map<String, dynamic>> deliveryLogsMapList =
          deliveryLogs.map((log) => log.toMap()).toList();

      // Add the delivery logs to the list
      allDeliveryLogs.addAll(deliveryLogsMapList);

      // Store the deliveryLogs in Hive
      await storeUniqueLogsInHive(deliveryLogs);

      // Close the database connection
      await database.close();
    } catch (e) {
      closeCustomLoadingDialog();
      showCustomSnackBar('Error downloading file: $fileName - $e');
      // Delete the corrupted file
      await localFile.delete();
      print('Corrupted file deleted: $fileName');
    }
  }
} catch (e) {
  closeCustomLoadingDialog();
  showCustomSnackBar("Error: $e");
  print(e);
} finally {
  closeCustomLoadingDialog();
  print("Disconnecting from FTP server...");
  await ftpConnect?.disconnect();

  isDownloading = false;
  downloadProgress = 0.0;
}

// Print the retrieved data
print('All Delivery Logs: $allDeliveryLogs');
closeCustomLoadingDialog();
}
i have also tried to give static path for single file to download then also i get error i would love if some one say what the issue

How to use listDirectoryContent in last version?

Old one had args like:

ftpConnect!.listDirectoryContent(cmd: DIR_LIST_COMMAND.LIST)

new one have mention about cmd but do not accept args:

  /// Returns the content of the current directory
  /// [cmd] refer to the used command for the server, there is servers working
  /// with MLSD and other with LIST
  Future<List<FTPEntry>> listDirectoryContent() {
    return FTPDirectory(_socket).directoryContent();
  }

And on new I am getting an error:

FTPConnectException: Connection refused.  (Response: 500 Unknown command.)

FTPEntry not a type

Hello,

I am getting a weird error in my project using your package for the first time:

The name 'FTPEntry' isn't a type, so it can't be used as a type argument.
Try correcting the name to an existing type, or defining a type named 'FTPEntry'.dartnon_type_as_type_argument

ERROR WHEN UPLOADING AN IMAGE TO FTP - FLUTTER : LateInitializationError.

Future<bool> guardarImagenFTP({required String ruta}) async {
    try {
      print('INICIO DE GUARDAR IMAGENEN FTP ...');
      final ftpConnect = FTPConnect('SERVER',
          user: 'USER', pass: 'PASSWORD');
      await ftpConnect.changeDirectory('/DIR1/DIR2/DIR3');
      final fileToUpload = File(ruta);
      print('CONECTANDO A FTP ...');
      await ftpConnect.connect();
      print('SUBIENDO IMAGEN...');
      final res = await ftpConnect.uploadFile(fileToUpload);
      await ftpConnect.disconnect();
      return res;
    } catch (e) {
      print('Error uploading file: ${e.toString()}');
      return false;
    }
  }

I have this problem when trying to upload an image via FTP, please help me.
LateInitializationError: Field '_socket@1477506163' has not been initialized.
ftpconnect version: ftpconnect: ^2.0.5

[REQUEST] Ability to transfer folders/directories instead of just files

I am making a switch mod manager which uses FTP to transfer mods to the switch. Only problem is, mods are usually raw folders and the only way to transfer files right now is one by one with creating directories based on the contents of a zip file. All around, this would be a great feature to add.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.