How to Read a docx file text from google drive? - flutter

Future<void> _loadFileContent() async {
final file = File(widget.filePath);
final extension = file.path.split('.').last.toLowerCase();
if (extension == 'pdf') {
final pdf = await PDFDoc.fromFile(file);
final pages = await pdf.pages;
final texts = await Future.wait(pages.map((page) => page.text));
_fileContent = texts.join('\n');
} else if (extension == 'txt') {
_fileContent = await file.readAsString();
// var decoded = base64.decode( _fileContent);
} else if (extension == 'docx') {
} else {
throw Exception('Unsupported file extension: $extension');
}
setState(() {
_isLoading = false;
});
How to Read a docx file text from google drive? How to implement with use of libary any suggection

Related

'file.absolute.existsSync()': is not true on uploading multiple files to storage flutter firebase

I'm trying for so long to upload multiple selected files to firebase storage but getting the same error again and again.
I'm picking up multiple files, they are getting picked just fine I've printed files they are going to the List just fine but when it comes to uploading it gives this error
Unhandled Exception: 'package:firebase_storage/src/reference.dart': Failed assertion: line 127 pos 12: 'file.absolute.existsSync()': is not true.
This error is coming on my uploadTask which is
UploadTask uploadTask = storageReference.putFile(File(fileNames![i]));
I've tried so much but couldn't do so. If anyone knows what I'm doing wrong please let me know.
Here's the complete of the code
List<String>? fileNames;
List<String> downloadUrls = [];
bool isUploading = false;
#override
Widget build(BuildContext context) {
Future<void> filePicker() async {
FilePickerResult? result =
await FilePicker.platform.pickFiles(allowMultiple: true);
if (result != null) {
setState(() {
fileNames =
result.paths.map((path) => path!.split('/').last).toList();
});
}
}
Future<void> uploadFiles() async {
setState(() {
isUploading = true;
});
for (int i = 0; i < fileNames!.length; i++) {
String fileName = fileNames![i];
String filePath = 'files/$fileName';
final storageReference =
FirebaseStorage.instance.ref().child('reports/$filePath');
UploadTask uploadTask = storageReference.putFile(File(fileNames![i]));
await uploadTask.whenComplete(() {
storageReference.getDownloadURL().then((fileURL) {
downloadUrls.add(fileURL);
});
});
}
setState(() {
isUploading = false;
});
}

Flutter - How to save and play a recorded audio file?

I, for the life of me, can't figure this out. All I am trying to do is record an audio (as in a sound/voice recorder) and later be able to play it.
Recorder class:
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
//String _pathToAudio = '/sdcard/myAudio.aac';
String _fileName = 'myAudio.aac';
String _path = "/storage/emulated/0";
class Recorder {
FlutterSoundRecorder? _recorder;
bool _isRecorderInitialized = false;
bool get isRecording => _recorder!.isRecording;
Future init() async {
_recorder = FlutterSoundRecorder();
//final directory = "/sdcard/downloads/";
//Directory? extStorageDir = await getExternalStorageDirectory();
//String _path = directory.path;
final status = await Permission.microphone.request();
if (status != PermissionStatus.granted) {
throw RecordingPermissionException('Recording permission required.');
}
await _recorder!.openAudioSession();
_isRecorderInitialized = true;
}
void _writeFileToStorage() async {
File audiofile = File('$_path/$_fileName');
Uint8List bytes = await audiofile.readAsBytes();
audiofile.writeAsBytes(bytes);
}
void dispose() {
_recorder!.closeAudioSession();
_recorder = null;
_isRecorderInitialized = false;
}
Future record() async {
if (!_isRecorderInitialized) {
return;
}
print('recording....');
await _recorder!.startRecorder(
toFile: '$_fileName',
//codec: Codec.aacMP4,
);
}
Future stop() async {
if (!_isRecorderInitialized) {
return;
}
await _recorder!.stopRecorder();
_writeFileToStorage();
print('stopped....');
}
Future toggleRecording() async {
if (_recorder!.isStopped) {
await record();
} else {
await stop();
}
}
}
Currently the error I am getting is "Cannot open file, path = '/storage/emulated/0/myAudio.aac' (OS Error: No such file or directory, errno = 2)".
I am using flutter_sound
Try initializing your file path by using path_provider.
Add these 2 lines to the beginning of your init function.
final directory = await getApplicationDocumentsDirectory();
_path = directory.path; // instead of "/storage/emulated/0"
Not sure how you're trying to access and play that file but on my end it at least cleared the error.
String _fileName = 'Recording_';
String _fileExtension = '.aac';
String _directoryPath = '/storage/emulated/0/SoundRecorder';
This is what I have currently and it's working.
void _createFile() async {
var _completeFileName = await generateFileName();
File(_directoryPath + '/' + _completeFileName)
.create(recursive: true)
.then((File file) async {
//write to file
Uint8List bytes = await file.readAsBytes();
file.writeAsBytes(bytes);
print(file.path);
});
}
void _createDirectory() async {
bool isDirectoryCreated = await Directory(_directoryPath).exists();
if (!isDirectoryCreated) {
Directory(_directoryPath).create()
// The created directory is returned as a Future.
.then((Directory directory) {
print(directory.path);
});
}
}
void _writeFileToStorage() async {
_createDirectory();
_createFile();
}

readAsBytesSync is incomplete

Since I can't convert convert a file directly from url (e.g File(url)).
I am downloading the file and then use the temp file path.
I tried different files : images, pdfs and it's still incomplete.
Am I doing something wrong here?
Future<String> downloadFile() async {
print(imgUrl);
Dio dio = Dio();
try {
var dir = await getApplicationDocumentsDirectory();
await dio.download(imgUrl, "${dir.path}/${widget.name}.pdf",
onReceiveProgress: (rec, total) {});
path = "${dir.path}/${widget.name}.pdf";
setState(() {
downloading = false;
progressString = "Completed";
});
if (path != null) {
List<int> imageBytes = File(path).readAsBytesSync();
print("NEW BYTE : $imageBytes");
}
} catch (e) {
print(e);
}
return path;
}
Checkout this solution:-
https://gist.github.com/Nitingadhiya/3e029e2475eeffac311ecd76f273941f
Uint8List? _documentBytes;
getPdfBytes() async {
_documentBytes = await http.readBytes(Uri.parse('https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf'));
return _documentBytes;
}
Future<void> readPDf() async {
//Load the existing PDF document.
Uint8List documentInBytes = await getPdfBytes();
final PdfDocument document = PdfDocument(inputBytes: documentInBytes);
//Get the existing PDF page.
final PdfPage page = document.pages[0];
//Draw text in the PDF page.
page.graphics.drawString('Hello World!', PdfStandardFont(PdfFontFamily.helvetica, 12), brush: PdfSolidBrush(PdfColor(0, 0, 0)), bounds: const Rect.fromLTWH(0, 0, 150, 20));
//Save the document.
final List<int> bytes = await document.save(); //document.saveSync();
await saveAndLaunchFile(bytes, 'Invoice.pdf');
//Dispose the document.
document.dispose();
}
Future<void> saveAndLaunchFile(List<int> bytes, String fileName) async {
//Get the storage folder location using path_provider package.
String? path;
if (Platform.isAndroid || Platform.isIOS || Platform.isLinux || Platform.isWindows) {
final Directory directory = await path_provider.getApplicationSupportDirectory();
path = directory.path;
} else {
path = await PathProviderPlatform.instance.getApplicationSupportPath();
}
final File file = File(Platform.isWindows ? '$path\\$fileName' : '$path/$fileName');
await file.writeAsBytes(bytes, flush: true);
if (Platform.isAndroid || Platform.isIOS) {
//Launch the file (used open_file package)
// await open_file.OpenFile.open('$path/$fileName');
} else if (Platform.isWindows) {
await Process.run('start', <String>['$path\\$fileName'], runInShell: true);
} else if (Platform.isMacOS) {
await Process.run('open', <String>['$path/$fileName'], runInShell: true);
} else if (Platform.isLinux) {
await Process.run('xdg-open', <String>['$path/$fileName'], runInShell: true);
}
}

Prevent Concurrent Access to File in Dart

I am creating a disk cache and I faced problem while running flutter tests cause by json.decode() but I found that the problem is that the same file is being read twice at the same time.
Here is the code for the disk cache class:
import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:the_chef/repositories/cache/base_cache.dart';
class DiskCache<V> extends BaseCache<List<String>, V> {
String directoryPath;
DiskCache({
BaseCache<List<String>, V> other,
}) {
next = other;
}
Future<V> _get(List<String> path) async {
print("get $path");
var val;
var file;
file = await _exists(path);
if (file != null) {
print("start");
var str = await file.readAsString();
val = json.decode(str);
print("end get $path");
return val;
}
val ??= next?.get(path);
if (val != null) {
await _createFile(file);
var bytes = json.encode(val);
await file.writeAsString(bytes);
}
if(val == null) {
print("notfound");
}
return val;
}
Future<V> get(List<String> path) async {
var x = await _get(path);
return x;
}
#override
Future<void> set(List<String> path, V value) async {
print("set $path");
final file = await _createFileFromPath(path);
var bytes = json.encode(value);
await file.writeAsString(bytes);
next?.set(path, value);
print("end set $path");
}
#override
Future<void> evict(List<String> path) async {
print("evict $path");
final file = await _localFile(path);
if (await file.exists()) {
await file.delete();
} else {
await file.delete(recursive: true);
}
await next?.evict(path);
}
Future<File> _exists(List<String> path) async {
var file = await _localFile(path);
return (await file.exists()) ? file : null;
}
Future<File> _localFile(List<String> filePath) async {
final path = await _localPath();
return File('$path/${filePath.join('/')}');
}
Future<String> _localPath() async {
if (directoryPath != null) {
return directoryPath;
}
directoryPath = (await getApplicationDocumentsDirectory()).path;
return directoryPath;
}
Future<File> _createFileFromPath(List<String> path) async {
var file = await _localFile(path);
await _createFile(file);
return file;
}
Future<void> _createFile(File file) async {
file.createSync(recursive: true);
}
}
It would be very great if you have any suggestion of how to improve the cache or have any other advices.
Thanks in advance.

Flutter web upload file

I want to upload files using Flutter web, but I encountered some problems, my steps are as follows:
/// choose file
void _chooseFile() {
InputElement uploadInput = FileUploadInputElement();
uploadInput.accept = ".mp4";
uploadInput.multiple = true;
uploadInput.click();
uploadInput.onChange.listen((event) {
final files = uploadInput.files;
if (files.length == 1) {
final file = files[0];
final reader = FileReader();
reader.onLoadEnd.listen((event) {
print('loaded: ${file.name}');
print('type: ${reader.result.runtimeType}');
print('file size = ${file.size}');
_uploadFile(file);
});
reader.onError.listen((event) {
print(event);
});
reader.readAsArrayBuffer(file);
}
});
}
/// upload file
/// file: in dart:html package not in dart:io package
void _uploadFile(File file) async {
FormData data = FormData.fromMap({
'file': MultipartFile.fromBytes(
List<int>, // -----------------------------> problem line
filename: file.name,
)
});
Dio dio = new Dio();
dio.post('upload file url', data: data, onSendProgress: (count, total) {
print('$count ==> $total');
}).then((value) {
print('$value');
}).catchError((error) => print('$error'));
}
The problem is that MultipartFile.fromBytes(List<int> value, {...}), but I don't know how to conver file ( in dart:html not in dart:io ) to List<int>.
Thanks!!!
You need to convert the reader, as below:
List<int> _selectedFile;
Uint8List _bytesData;
void _handleResult(Object result) {
setState(() {
_bytesData = Base64Decoder().convert(result.toString().split(",").last);
_selectedFile = _bytesData;
});
}
call the func:
_handleResult(reader.result);
then, pass _bytesData to your MultipartFile.fromBytes(...) or have return func type as List<int> and call it anywhere you need.
For example, this is what I have done to get the image:
List<int> imageFileBytes;
/// Browse Image:
_setImage(int index) async {
html.InputElement uploadInput = html.FileUploadInputElement();
uploadInput.multiple = false;
uploadInput.draggable = true;
uploadInput.accept = 'image/*';
uploadInput.click();
html.document.body.append(uploadInput);
uploadInput.onChange.listen((e) {
final files = uploadInput.files;
final file = files[0];
final reader = new html.FileReader();
reader.onLoadEnd.listen((e) {
var _bytesData = Base64Decoder().convert(reader.result.toString().split(",").last);
setState(() {
imageFileBytes = _bytesData;
});
});
reader.readAsDataUrl(file);
});
uploadInput.remove();
}
InputElement uploadInput = FileUploadInputElement();
uploadInput.accept = 'image/*';
uploadInput.click();
uploadInput.onChange.listen(
(changeEvent) {
final file = uploadInput.files.first;
final reader = FileReader();
reader.readAsDataUrl(file);
reader.onLoadEnd.listen(
(loadEndEvent) async {
_file = file;
setState(() {});
},
);
},
);
That code Work fine for me.