I want to download an image from URL and save it into the SD folder.
what I have tried:
I have tried this code it works fine but it store in
/storage/emulated/0/Android/data/com.example.college_services/files/Images
but i want to store in /Sdcard/Images
_dowloadimg() async{
var url = widget.imageURL;
var response = await get(url);
var documentDirectory = await getExternalStorageDirectory();
var firstPath = documentDirectory.path + "/Images";
var filePathAndName = documentDirectory.path + '/Images/img_${i++}.jpg';
await Directory(firstPath).create(recursive: true);
File file2 = new File(filePathAndName);
file2.writeAsBytesSync(response.bodyBytes);
}
As path_provider doesn't provide download directory path. You will need to call native apis.
Use These packages to do that:-
downloads_path_provider
OR
ext_storage
In case of 1st one the code will look like this:-
var documentDirectory = await DownloadsPathProvider.downloadsDirectory;
In case of 2nd one the code will look like this:-
var documentDirectory = await ExtStorage.getExternalStoragePublicDirectory(ExtStorage.DIRECTORY_DOWNLOADS);
Related
I am using the Flutter Image Compression package
https://pub.dev/packages/flutter_image_compress
to compress some images with the below code.
it is working correctly if the picked photos are anywhere on the device, except the folder "Internal Storage/Android"
if the image is anywhere inside this folder or its subfolders, the compression result is null.
while these Folders contain all images received through WhatsApp, users will need to use them.
any reason why? or how to solve it?
My assumption could be access permission to this folder but don't know if this is true.
for (int i = 0; i < imageslist.length; i++) {
final filePath = imageslist[i].absolute.path;
var extensionString =
filePath.toString().substring(filePath.toString().length - 3);
if (extensionString == "jpg" || extensionString == "peg") {
final lastIndex = filePath.lastIndexOf(new RegExp(r'.jp'));
final splitted = filePath.substring(0, (lastIndex));
final outPath = "${splitted}_out${filePath.substring(lastIndex)}";
var result = await FlutterImageCompress.compressAndGetFile(
imageslist[i].absolute.path,
outPath,
quality: 50,
);
print(result);
I found that the problem is in saving the file to folder of whatsapp, so instead I made all my photos to be saved after compression in a temp folder.
using path_provider package
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
I'm using ImageGallerySaver for downloading gif files.
At Android platform, It takes good.
But iOS platform, gif files save as jpg. So, files not animated...
please help me.
My code likes this.
var appDocDir = await getTemporaryDirectory();
String savePath = appDocDir.path + "/temp.gif";
await Dio().download(imgUrl, savePath);
final result = await ImageGallerySaver.saveFile(savePath);
Below Code i have created for local caching using path provider
String fileName="pathString.json";
var dir=await getTemporaryDirectory();
File file=File(dir.path+"/"+fileName);
if(!file.existsSync()) {
final http.Response response = await http.get(
Uri.parse("https://*************.herokuapp.com/*********"));
file.writeAsStringSync(
response.body, flush: true, mode: FileMode.write);
final data = file.readAsStringSync();
responseData = json.decode(data);
}else{
final data = file.readAsStringSync();
responseData = json.decode(data);
final http.Response response = await http.get(
Uri.parse("https://**************.herokuapp.com/*********"));
file.writeAsStringSync(
response.body, flush: true, mode: FileMode.write);
}
for first time, File can be Created. But For Second time.. Once File is created, and API fetches latest response with updated data, Cache file not get overwritten.
It would be great, if anyone can help on this..
Thanks in Advance.
i suppose that in your case happening something similar, to my situation:
For flutter Image class i found that, it use ImageCache for caching images, so when you rewrite Image and save it in filesystem, image will look the same until you restart app or invalidate cache.
Code that i wrote for cache invalidation for image:
import 'dart:io';
import 'package:flutter/material.dart';
// imgBytes - raw image bytes here empty just for example
// location - path to image in fs
updateImage(Uint8List imgBytes) async {
var file = File(location);
await file.writeAsBytes(imgBytes, mode: FileMode.write); // rewrite file content
var img = Image.file(file); // create Image class
img.image.evict(); // invalidate cache key for this image
}
Here I want to share image which I get through API. I tried different method for this functionality but I did not get any solution because every solutions have for only one image.
Exactly, I get multiple image from Url and I open any particular image in next page. So, I want to share that image which I opened in another page.
I tried for sharing image but I could not did this. Whenever I try to share that image, Image url share with sharing option on device but I want share image not URl of image How I can accomplish this?
You have to download the image like this:
http.Response response = await http.get(url);
then create an image on the device using the downloaded image like this (Read and Write Files):
final directory = await getTemporaryDirectory();
final path = directory.path;
final file = File('$path/image.png');
file.writeAsBytes(response.bodyBytes);
The getTemporaryDirectory() is in the plugin path_provider. Now, you have the image you'd like to share stored in the temporarily as "image.png" and you can use the share_plus plugin to share the image like this:
Share.shareFiles(['$path/image.png']);
Thanks to #abdulrazak, At first, you have to download the image in a temporary path & then you can share the image as you want. used Dio to download the image & share_plus for sharing
void _shareNetworkImage(String url) async {
Directory tempDir = await getTemporaryDirectory();
final path = '${tempDir.path}/test.jpeg';
await Dio().download(url, path);
Share.shareFiles([path]);
}
You can use the esys_flutter_share plugin.
Install it, and then get dependencies:
dependencies:
esys_flutter_share: ^1.0.2
Import the plugin to your code:
import 'package:esys_flutter_share/esys_flutter_share.dart';
Use the below code:
var request = await HttpClient().getUrl(Uri.parse('https://yourImageURL.jpg'));
var response = await request.close();
Uint8List bytes = await consolidateHttpClientResponseBytes(response);
await Share.file('ESYS AMLOG', 'amlog.jpg', bytes, 'image/jpg');
I am using ImagePickerWeb and upload an images in Storage. For display this images I am using url. If user change image, how to update in storage? The first need delete previous image and upload again?
Future uploadImg() async {
var timekey = DateTime.now();
fb.StorageReference storageReference =
fb.storage().ref('imgProduct/${timekey.toString()}.jpg');
fb.UploadTaskSnapshot uploadTask = await storageReference
.put(_image1, fb.UploadMetadata(contentType: 'image/jpg'))
.future;
var imageUrl = await uploadTask.ref.getDownloadURL();
url = imageUrl.toString();
print('Image Url' + url);
}
you need to update the database with the new photo url and then delete the old image from firebase storage.