I'm developing an application where the user of my App must upload images to Firebase Storage, and for that, they need to be in File format.
Part of the images come from the web, that is, they were obtained through the Image.network()
method. Another part comes from the cell phone gallery, and was obtained by the ImagePicker
package.
Even coming from different sources, all images are being grouped in a List<Image>
. Now, I need to upload this list of images to Storage, but for that I need to convert them to File and I don't know how to do that, could anyone help?
CodePudding user response:
You can download the image and save the file in the followwing way.
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
Future<File> _fileFromImageUrl() async {
final response = await http.get('https://example.com/xyz.jpg');
final documentDirectory = await getApplicationDocumentsDirectory();
final file = File(join(documentDirectory.path, 'imagetest.png'));
file.writeAsBytesSync(response.bodyBytes);
return file;
}
CodePudding user response:
First you should save image from network url to file, it is better like this
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
Future<File> _fileFromImageUrl() async {
final response = await http.get('https://example.com/abc.jpg');
final documentDirectory = await getApplicationDocumentsDirectory();
final file = File(join(documentDirectory.path, 'imagetest.png'));
file.writeAsBytesSync(response.bodyBytes);
return file;
}
After that add this to you image list with the image taken from image picker. https://pub.dev/packages/image_picker
import 'package:image_picker/image_picker.dart';
final ImagePicker _picker = ImagePicker();
final XFile? image = await _picker.pickImage(source:ImageSource.gallery);