How to upload a folder directly with ftpconnect in flutter - flutter

In the ftpconnect package, there is a way to upload files and create directories. I need to be able to upload a raw folder or somehow extract a zip folder to the remote location.
Future<void> _uploadStepByStep(File fileToUpload) async {
try {
await _ftpConnect.connect();
if(await _ftpConnect.checkFolderExistence('ultimate/mods'))
{
await _log('exists');
await _ftpConnect.changeDirectory('ultimate/mods');
await _log(_ftpConnect.currentDirectory().toString());
bool res = await _ftpConnect.uploadFileWithRetry(fileToUpload, pRetryCount: 2);
print(res);
}
await _ftpConnect.disconnect();
} catch (e) {
await _log('Error: ${e.toString()}');
}
}
Is there any way to upload an entire folder or unzip and upload every part of the contents of a zip file?

Related

Delete file permanantly from list view in flutter

I list all pdf files from storage and now I want to delete multi-files in my flutter list . as well as from the device file manager. I am using this function but when I delete and restart the app the file comes again
This is the function I'm using to delete the list:
void deleteItems() {
var list = myMultiSelectController.selectedIndexes;
list.sort((b, a) => a.compareTo(b));
list.forEach((element) {
files.removeAt(element);
});
setState(() {
myMultiSelectController.set(files.length);
});
}
files.removeAt(element); Just removes file from the list. You need to actually delete file from device.
eg
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
print('path ${path}');
return File('$path/counter.txt');
}
Future<int> deleteFile() async {
try {
final file = await _localFile;
await file.delete();
} catch (e) {
return 0;
}
}
See more here from SO answer

Get a list of files from the local storage and display it as a list in flutter web:

I've been building an ios app and in it, it'll download a bunch of pdf from an API and save it to the local storage using the path_provider package in flutter:
This is the code I use to fetch the path:
Future<String> get localPath async {
final directory = await getApplicationDocumentsDirectory();
currentDir.value = directory.path;
return directory.path;}
And this is how I save it to the device:
Future<void> saveFilesToLocal(String url, String fileName) async {
try {
final path = await localPath;
final file = File('$path/$fileName');
if (await file.exists() == false) {
final response = await Dio().get(url,
options: Options(
responseType: ResponseType.bytes,
followRedirects: false,
receiveTimeout: 0));
final raf = file.openSync(mode: FileMode.write);
raf.writeFromSync(response.data);
await raf.close();
} else {
print("file already exists");
}
} catch (e) {
print('error: $e');
}
}
After I download and save the files to the storage, it'll be displayed as a gridview in the home page. To fetch that list of files I use this:
List<FileSystemEntity> files = [];
Future<void> getFilesList() async {
files.clear();
final path = await localPath;
Directory dir = Directory('$path');
files =
dir.listSync(recursive: true, followLinks: false);
update();
}
And all of this works fine in the ios device. But the current issue I'm facing while trying to run it on web is:
The package path_provider is not available for flutter web. I've been asked to create it as a web app too and I can't find an alternative for it. While looking for one I saw a post saying flutter web won't allow access to a device's local storage like that so it's not possible. Is it true? Is there a workaround? If it's about security, the app will only be run on specific devices. It won't be given to the public.

Accesing downloaded files from a Flutter app

I am working on an app that should manage downloaded files.
For now I am able to download a file on both platforms, but I would need to know how can I get the downloaded files from the device.
This is the code used to download a file from Internet.
Future<void> downloadFile() async {
bool downloading = false;
var progressString = "";
final imgUrl = "https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4";
Dio dio = Dio();
try {
var dir = await getApplicationDocumentsDirectory();
print("path ${dir.path}");
await dio.download(imgUrl, "${dir.path}/demo.mp4",
onReceiveProgress: (rec, total) {
print("Rec: $rec , Total: $total");
downloading = true;
progressString = ((rec / total) * 100).toStringAsFixed(0) + "%";
});
} catch (e) {
print(e);
}
downloading = false;
progressString = "Completed";
print("Download completed");
}
The path print output for Android is:
path /data/user/0/red.faro.labelconciergeflutter/app_flutter
The path print output for iOS is:
path /var/mobile/Containers/Data/Application/9CFDC9E3-D9A9-4594-901E-427D44E48EB9/Documents
What I need is to know how can an app user access the downloaded files when the app is closed or there is no internet connection to open the file from the original URL?
For getting files from the device you may use file_picker package.
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
File file = File(result.files.single.path);
} else {
// User canceled the picker
}
You also can use the File class from the dart:io library.
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/counter.txt');
}
If your goal is to access commonly used locations on the device’s file system you can use the path_provider plugin.
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path

Flutter web - Uploading image to firebase storage

I am using the firebase_storage: ^8.0.6 package on flutter web. I want to upload image to firebase storage that I get using FilePicker package.
The problem is that the new package uses the putFile() method to upload files. But File from dart:io doesn't work on flutter web and it also doesn't accept the File object from dart:html.
I can upload image as Blob using the putBlob() method but then it doesn't upload it as image type but it's type is application/octet-stream. I don't want to upload the image file as a blob.
Future<String> uploadImage(PlatformFile file) async {
try {
TaskSnapshot upload = await FirebaseStorage.instance
.ref(
'events/${file.name}-${DateTime.now().toIso8601String()}.${file.extension}')
.putBlob(Blob(file.bytes));
String url = await upload.ref.getDownloadURL();
return url;
} catch (e) {
print('error in uploading image for : ${e.toString()}');
return ';
}
}
How to fix this issue?
You can use the putData() method to send the image and set it's metadata as a image.
Future<String> uploadImage(PlatformFile file) async {
try {
TaskSnapshot upload = await FirebaseStorage.instance
.ref(
'events/${file.path}-${DateTime.now().toIso8601String()}.${file.extension}')
.putData(
file.bytes,
SettableMetadata(contentType: 'image/${file.extension}'),
);
String url = await upload.ref.getDownloadURL();
return url;
} catch (e) {
print('error in uploading image for : ${e.toString()}');
return '';
}
}
putData() method takes Uint8List by default.
Uploading images using TaskSnapshot is not working on my flutter web project.
I used firebase_storage: ^8.1.3 .
Following code is working for my web project.
String nameImage = DateTime.now().millisecondsSinceEpoch.toString();
Reference _reference = FirebaseStorage.instance
.ref()
.child('images/$nameImage.png}');
await _reference
.putData(
await image.readAsBytes(),
SettableMetadata(contentType: 'image/jpeg'),
)
.whenComplete(() async {
await _reference.getDownloadURL().then((value) {
user.profilePictureURL = value;
FireStoreUtils.firestore
.collection(USERS)
.doc(user.userID)
.update({'profilePictureURL': user.profilePictureURL});
});
});
You can still use .putFile when you use the File.fromUri() constructor and get the Uri from the PlatformFile object using Uri.dataFromBytes and passing the bytes to it.
The code below contains changes that should remove the error:
TaskSnapshot upload = await FirebaseStorage.instance
.ref(
'events/${file.name}-${DateTime.now().toIso8601String()}.${file.extension}')
.putFile(File.fromUri(Uri.dataFromBytes(file.bytes.toList())));

Download file to Device download folder in Flutter

I'm trying to download files in my flutter app using the dio plugin for which I have to specify a "savePath". But using path_provider I can only see ApplicationDocumentsDirectory, ExternalStorageDirectory etc. My idea is to simply show the file(pdf) in the device's Download Folder, so whenever the user wants to view the file, he just goes to the folder and clicks it.
Saving to ApplicationDocumentsDirectory (as I understood it) would require me to provide a link (of sorts) to the file in the app, meaning the user would have to open my app every time he wants to view files downloaded through my app.
I just want the files to be available in the DownLoads Folder, just like with so many files we download directly to the DownLoads Folder.
Am I missing something here? pls enlighten me!
Added this code on request from user in comments:
var dir;
Future < dynamic > downloadFile(url, filename) async {
Dio dio = Dio();
try {
// checkPermission();
//if(Externa)
dir = await getApplicationDocumentsDirectory();
if (dir.path != null)
print("url:$url");
print("path:${dir.path}/$filename");
if (await File("${dir.path}/$filename").exists()) {
setState(() {
filePath = "${dir.path}/$filename";
});
return;
}
await dio.download(url, "${dir.path}/$filename",
onReceiveProgress: (rec, total) {
print("Rec: $rec , Total: $total");
setState(() {
downloading = true;
progressString = ((rec / total) * 100).toStringAsFixed(0) + "%";
});
});
} catch (e) {
print("downloadErr:$e");
}
setState(() {
downloading = false;
progressString = "Concluido";
filePath = "${dir.path}/$filename";
});
}
You can use downloads_path_provider for it
https://pub.dev/packages/downloads_path_provider
import 'package:downloads_path_provider/downloads_path_provider.dart';
Future<Directory> downloadsDirectory = DownloadsPathProvider.downloadsDirectory;