Whenever I try to check for a folder's existence, it appropriately does but whenever I try to change the directory, it does not work. This is the code and it only prints the first 'exists' and not the second even though the directory /ultimate/mods does exist on the remote device. The remote device does not need a password(set to anonymous mode) so I don't think that permissions are an issue. If anyone can help it would be greatly appreciated.
import 'package:ftpconnect/ftpconnect.dart';
void main() async {
final FTPConnect _ftpConnect = FTPConnect(
"10.0.0.6",
user: "guiege",
port: 5000,
);
Future<void> _log(String log) async {
print(log);
await Future.delayed(Duration(seconds: 1));
}
Future<void> _uploadStepByStep() async {
try {
await _ftpConnect.connect();
if(await _ftpConnect.checkFolderExistence('ultimate'))
{
await _log('exists');
_ftpConnect.changeDirectory('ultimate');
if(await _ftpConnect.checkFolderExistence('mods'))
{
await _log('exists2');
}
}
await _ftpConnect.disconnect();
} catch (e) {
await _log('Error: ${e.toString()}');
}
}
Related
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
For image_picker MainActivity destruction I wanted to use other plugin to pick image. And I found wechat_camera_picker as an alternative. But there was a problem while capturing the image. The captured image saved on Local Storage after selecting the image. Here is my code.
Future<File> getImageByCamera(BuildContext context) async {
try{
final AssetEntity result = await CameraPicker.pickFromCamera(
context,
pickerConfig: CameraPickerConfig(
shouldDeletePreviewFile: true,
enableRecording: false,
textDelegate: EnglishCameraPickerTextDelegate(),
),
);
if(result != null){
File pickedFile = await result.file;
pickedFile = await compressFile(pickedFile);
return pickedFile;
}else{
return null;
}
}catch(error){
print(error);
return null;
}
}
Does anyone have any solution of this problem?
you can use the below function to delete the locally stored file.
Future<bool> deleteFile(File pickedFile) async {
try {
await pickedFile.delete();
return true;
} catch (e) {
return false;
}
}
You can check the Delete Function Documation for referenece.
I am using the flutter_sound package to record and play audio. On Flutter Web, on stopping the recording the recorder returns a path/URL of this type: blob:http://localhost:63986/b60f31ce-b94d-48c8-8a4a-2d939effe6d8
I want to upload the audio recording to Firebase Storage but dart.io can't be used for flutter-web so can't use the File method. Even after searching, I didn't find a way to achieve it. I don't know how to proceed. How can I write the audio to file and upload it to firebase?
My Code:
import 'dart:html' as html;
import 'dart:io' as io;
final recorder = FlutterSoundRecorder();
final player = FlutterSoundPlayer();
String fileName;
#override
void initState() {
super.initState();
initRecorder();
}
#override
void dispose() {
recorder.closeRecorder();
player.closePlayer();
super.dispose();
}
Future<void> initRecorder() async {
if (!kIsWeb) {
final status = await Permission.microphone.request();
if (status != PermissionStatus.granted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Grant Permission form mic first!')),
);
}
}
await recorder.openRecorder();
await player.openPlayer();
recorder.setSubscriptionDuration(Duration(milliseconds: 500));
}
Future<void> record() async {
fileName = DateTime.now().toString();
await recorder.startRecorder(toFile: fileName);
}
Future<void> stop() async {
path = await recorder.stopRecorder();
if (kIsWeb) {
if (path == null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Grant Permission for mic first!')),
);
} else {
// Get File from path and upload it to Firebase
print(path);
// not working for Web
// final audioFile = io.File(path);
// html.File() doesn't take path/Url as parameter but
// File(List<Object> fileBits, String fileName,[Map? options])
/*
await FirebaseStorage.instance
.ref()
.child('users/uploads/$fileName.mp3')
.putData(file!.bytes!);*/
}
} else if (!kIsWeb) {
if (path == null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Grant Permission for mic first!')),
);
} else {
//final audioFile = io.File(path);
// await FirebaseStorage.instance
// .ref()
// .child('users/uploads/$fileName.mp3')
// .putFile(audioFile);
}
}
}
I've been working on this for days, and I finally figured it out!
When you call startRecorder(toFile: audioLocation), audioLocation will be the location of the file after you call stopRecorder(), stored in html.window.sessionStorage (html as in import 'dart:html' as html;).
So you need to add import 'package:http/http.dart' as http;, create a fileName (whatever you want the file to be called in Firebase Storage), and then insert the following piece of code.
var ref = await storage.ref().child('path/to/file/$fileName');
Uri blobUri = Uri.parse(html.window.sessionStorage[audioFile]!);
http.Response response = await http.get(blobUri);
await ref.putData(response.bodyBytes, SettableMetadata(contentType: 'video/mp4'));
This might not be the best way, but it is the way I finally got it to work! Good luck!!
I want to display multiple Items in the list and store it in the ftp server. So far I can only store the first index, now I want when the user decides to take multiple photos, they can be stored also on the ftp server. So may you please help how can I loop through photos file list and achieve this: Check my code below
final photos = <File>[];
Future<void> fileUpload() async {
FTPConnect ftpConnect = FTPConnect('xxxxxxxx',
user: 'xxxxxxxxx',
pass: 'xxxxxxxxx',
port: xx,
//isSecured: false,
debug: true);
try {
File fileToUpload = await File(photos.first.path);
await ftpConnect.connect();
await ftpConnect.changeDirectory('public_html');
await ftpConnect.changeDirectory('assets');
await ftpConnect.changeDirectory('images');
await ftpConnect.changeDirectory('app');
await ftpConnect.sizeFile('$photos');
await ftpConnect.rename('CAP4077791735949912884.jpg', 'laptop.jpg');
await ftpConnect.uploadFile(fileToUpload);
await ftpConnect.disconnect();
} catch (e) {
//error
await _log('Error: ${e.toString()}');
}
}
Try putting the code in the loop with the length of the list of photos.
final photos = <File>[];
for (File photo in photos) {
// your code to upload file to the FTP server
}
A loop will do the trick:
Future<void> fileUpload() async {
FTPConnect ftpConnect = FTPConnect('x.x.x',
user: 'x',
pass: 'x',
port: 0,
//isSecured: false,
debug: true);
try {
File fileToUpload = await File(photos.first.path);
await ftpConnect.connect();
await ftpConnect.changeDirectory('public_html');
await ftpConnect.changeDirectory('assets');
await ftpConnect.changeDirectory('images');
await ftpConnect.changeDirectory('app');
await ftpConnect.sizeFile('$photos');
await ftpConnect.rename('CAP4077791735949912884.jpg', 'laptop.jpg');
photos.forEach((element) async {
File _file = File(element.path);
await ftpConnect.uploadFile(_file);
});
await ftpConnect.disconnect();
} catch (e) {
//error
debugPrint(e.toString());
}
}
I need to read and write files on Flutter.
Write works, but read not or I think it doesn't because the terminal output is flutter: Instance of 'Future<String>'.
What does it means?
This is the code :
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/hello.txt');
}
Future<File> writeHello() async {
final file = await _localFile;
// Write the file.
return file.writeAsString('HelloWorld');
}
Future<String> readHello() async {
try {
final file = await _localFile;
// Read the file.
return await file.readAsString();
} catch (e) {
// If encountering an error, return 0.
return "Can't read";
}
}
.
.
.
writeHello();
print(readHello());
Future<String> is of type Future hence you need to resolve the future, You can either await before printing or use .then() to resolve the Future.
Using await
String data = await readHello();
print(data);
Using .then()
readHello().then((data){ //resolve the future and then print data
print(data);
});
Note: There is no need to add extra "await" here on line 2 as you already are awaiting at line 1:
Future<String> readHello() async {
try {
final file = await _localFile; //Line 1
// Read the file.
return await file.readAsString(); //Line 2
} catch (e) {
// If encountering an error, return 0.
return "Can't read";
}
}
Now I got it, I understood what you said me thank you!
I created a new function that mix write and read.
The problem is that I called async functions in my program body where I can't use await , I should call them in other async functions to handle them in the right way.
I solved with this :
void _RWHello(String text) async {
writeHello();
print(await readHello());
}
.
.
.
_RWHello("HelloWorld");