Converting PlatformFile to File - flutter

I am using the package file_picker to select a PDF file from the device and uploading it to a remote server.
void capturarPDF() async{
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf'],
);
if(result == null) return;
PlatformFile file = result!.files.first ;
print("file ${file.path}");
_upload(file);
}
void _upload(File file) {
if (file == null) return;
setState(() {});
String base64Image = base64Encode(file.readAsBytesSync());
String fileName = file.path!.split("/").last;
String? mimeStr = lookupMimeType(file.path.toString());
var fileType = mimeStr!.split('/');
var tipo = "3";
http.post(Uri.parse(phpEndPoint), body: {
"image": base64Image,
"name": fileName,
"cod_sat": widget.codigo,
"tipo": tipo,
}).then((res) async {
setState(() {
});
}).catchError((err) {
print(err);
});
}
My issue is that at line _upload(file); I am getting the error:
The argument type 'PlatformFile' can't be assigned to the parameter type 'File'
Is there a way to convert a PlatformFile generated by the package file_picker to the type File needed to upload the file?

PlatformFile has a path reference to the file, you can take that path and set a File object with that path like this:
final path = file.path
_upload(File(path));

Related

How to get file stream value from "file_picker" flutter web?

I need to pick an image from gallery and also have an another field for drag image.
For drag and drop field I used flutter_dropzone.
and used getFileStream(event) data to upload data into server.But file_picker: ^5.2.4 is used to pick image from gallery.So how to get filestream data from this package.
I got bytes but that is not working I needed filestream value
Code using file_picker
void chooseImage() async {
pickedFile = await FilePicker.platform.pickFiles(
type: FileType.custom,
withReadStream: true,
allowedExtensions: [
'jpg','jpeg','png'
]
);
if (pickedFile != null) {
try {
base64 = pickedFile!.files.first.bytes;
base64String.value=base64.toString();
String mime = pickedFile!.files.first.extension.toString();
getS3url("image/$mime" ,base64String.value,from: "cameraIcon");
//withReadStream
//getFileStream(event);
} catch (err) {
print(err);
}
} else {
}
}
Copied from https://github.com/miguelpruivo/flutter_file_picker/wiki/FAQ
import 'package:file_picker/file_picker.dart';
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';
import 'package:mime/mime.dart';
void main() async {
final result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: [
'jpg',
'png',
'mp4',
'webm',
],
withData: false,
withReadStream: true,
);
if (result == null || result.files.isEmpty) {
throw Exception('No files picked or file picker was canceled');
}
final file = result.files.first;
final filePath = file.path;
final mimeType = filePath != null ? lookupMimeType(filePath) : null;
final contentType = mimeType != null ? MediaType.parse(mimeType) : null;
final fileReadStream = file.readStream;
if (fileReadStream == null) {
throw Exception('Cannot read file from null stream');
}
final stream = http.ByteStream(fileReadStream);
final uri = Uri.https('siasky.net', '/skynet/skyfile');
final request = http.MultipartRequest('POST', uri);
final multipartFile = http.MultipartFile(
'file',
stream,
file.size,
filename: file.name,
contentType: contentType,
);
request.files.add(multipartFile);
final httpClient = http.Client();
final response = await httpClient.send(request);
if (response.statusCode != 200) {
throw Exception('HTTP ${response.statusCode}');
}
final body = await response.stream.transform(utf8.decoder).join();
print(body);
}

upload file in flutter web by file_picker

i use file_picker: ^4.2.0 show package for my application.
when i get web release as html, get some Error.
error: path always null in web release
my code to get file:
Future getFile() async {
FilePickerResult? result = await FilePicker.platform.pickFiles(
withReadStream: true,
type: FileType.custom,
allowedExtensions: ['png', 'jpeg', 'jpg', 'pdf'],
);
if (result != null) {
PlatformFile file = result.files.single;
setState(() {
_file = File(file.path.toString());
_filePath = file.path;
});
_uploadFile();
} else {
// file not choose
}
}
i use https://pub.dev/packages/file_picker but in flutter web path not suppor;
you should to use bytes;
i save file bytes in var _fileBytes and use in request;
var request = http.MultipartRequest('POST', Uri.parse('https://.....com'));
request.headers.addAll(headers);
request.files.add(
http.MultipartFile.fromBytes(
'image',
await ConvertFileToCast(_fileBytes),
filename: fileName,
contentType: MediaType('*', '*')
)
);
request.fields.addAll(fields);
var response = await request.send();
function ConvertFileToCast:
ConvertFileToCast(data){
List<int> list = data.cast();
return list;
}
it`s work for me :)

I am using the Flutter Plugin Image_picker to choose images so that I want to upload image after selected the image

this is my code
Future<File> _imageFile;
void _onImageButtonPressed(ImageSource source) async {
setState(() {
_imageFile = ImagePicker.pickImage(source: source);
});
}
I find this code in flutter documentation but its not work
var uri = Uri.parse("http://pub.dartlang.org/packages/create");
var request = new http.MultipartRequest("POST", url);
request.fields['user'] = 'nweiz#google.com';
request.files.add(new http.MultipartFile.fromFile(
'package',
new File('build/package.tar.gz'),
contentType: new MediaType('application', 'x-tar'));
request.send().then((response) {
if (response.statusCode == 200) print("Uploaded!");
});
I used file_picker library to pick files. you can use this for pick images as well.
Future getPdfAndUpload(int position) async {
File file = await FilePicker.getFile(
type: FileType.custom,
allowedExtensions: ['pdf','docx'], //here you can add any of extention what you need to pick
);
if(file != null) {
setState(() {
file1 = file; //file1 is a global variable which i created
});
}
}

Make PlatformFile into File in Flutter using File Picker

I am using the File Picker Plugin to choose a file from a device. The file is chosen in the datatype of a PlatformFile, but I want to send the file to Firebase Storage and I need a regular File for that. How can I convert the PlatformFile into a File so that I can send it to Firebase Storage? Here is the code:
PlatformFile pdf;
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
void _trySubmit() async {
final isValid = _formKey.currentState.validate();
if (isValid) {
_formKey.currentState.save();
final ref = FirebaseStorage.instance
.ref()
.child('article_pdf')
.child(title + '-' + author + '.pdf');
await ref.putFile(pdf).onComplete; // This throws an error saying that The argument type 'PlatformFile' can't be assigned to the parameter type 'File'
}
}
void _pickFile() async {
FilePickerResult result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf'],
);
if (result != null) {
pdf = result.files.first;
}
}
Try this:
PlatformFile pdf;
final File fileForFirebase = File(pdf.path);
Happy coding! :)
If you're on a web app, you can post image files to Firestore with flutter_file_picker: (Taken from the FAQ page): https://github.com/miguelpruivo/flutter_file_picker/wiki/FAQ
// get file
final result = await FilePicker.platform.pickFiles(type: FileType.any, allowMultiple:
false);
if (result.files.first != null){
var fileBytes = result.files.first.bytes;
var fileName = result.files.first.name;
// upload file
await FirebaseStorage.instance.ref('uploads/$fileName').putData(fileBytes);
}
This works
File(platformFile.name)
Just be sure not duplicates in the file names in your logic.

how to read imported file flutter

so i have a function pickFile() :
Future pickFile() async {
FilePickerResult result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['txt'],
);
if (result != null) {
setState(() {
importfile = File(result.files.single.path);
});
}
}
i have acces to documentsdirectory with :
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
but i don't know how to put the choosen file into my "importfile" variable :
File importfile;
i know right know i get the path to the file, but how to i actually get the txt content?
You can call readAsString method on file object. There are other methods like readAsStringSync, readAsLines, readAsLinesSync and openRead, those can be used as well.
File importedFile = File('some-file-path.txt');
String fileContent = await importedFile.readAsString();