How can I download an image from the network and save it in a locally directory?
To achieve this I would suggest you first to add the universal_html
package to your pubspec.yaml
because in the newer versions of Flutter you will get warnings for importing dart:html
.
In pubspec.yaml
:
dependencies:
flutter:
sdk: flutter
http: ^0.13.1 // add http
universal_html: ^2.0.8 // add universal_html
I created a fully working example Flutter web app, you can try it, but the only thing that interests you is the downloadImage
function.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// if you don't add universal_html to your dependencies you should
// write import 'dart:html' as html; instead
import 'package:universal_html/html.dart' as html;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final imageUrls = <String>[
'https://images.pexels.com/photos/208745/pexels-photo-208745.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
'https://images.pexels.com/photos/1470707/pexels-photo-1470707.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
'https://images.pexels.com/photos/2671089/pexels-photo-2671089.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
'https://images.pexels.com/photos/2670273/pexels-photo-2670273.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: GridView.count(
crossAxisCount: 3,
children: imageUrls
.map(
(imageUrl) => ImageCard(imageUrl: imageUrl),
)
.toList(),
),
);
}
}
class ImageCard extends StatefulWidget {
@override
_ImageCardState createState() => _ImageCardState();
final String imageUrl;
ImageCard({
@required this.imageUrl,
});
}
class _ImageCardState extends State<ImageCard> {
Future<void> downloadImage(String imageUrl) async {
try {
// first we make a request to the url like you did
// in the android and ios version
final http.Response r = await http.get(
Uri.parse(imageUrl),
);
// we get the bytes from the body
final data = r.bodyBytes;
// and encode them to base64
final base64data = base64Encode(data);
// then we create and AnchorElement with the html package
final a = html.AnchorElement(href: 'data:image/jpeg;base64,$base64data');
// set the name of the file we want the image to get
// downloaded to
a.download = 'download.jpg';
// and we click the AnchorElement which downloads the image
a.click();
// finally we remove the AnchorElement
a.remove();
} catch (e) {
print(e);
}
}
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () => downloadImage(widget.imageUrl),
child: Card(
child: Image.network(
widget.imageUrl,
fit: BoxFit.cover,
),
),
);
}
}
Yunet Luis Ruíz
Updated on December 29, 2022Comments
-
Yunet Luis Ruíz over 1 year
I'm trying to download an image from the network and save it locally in the Downloads folder of a computer. I need to achieve that for flutter web, I'm not sure how to do it.
I found some questions related to how to achieve download and save a file or an image for android and IOS, such as Flutter save a network image to local directory. I also took a look at How do I read and write image file locally for Flutter Web?. However, I don't see how those answers can help me.
I think that for IOS and Flutter I can use the following function without getting any error, but I don't know where the files are being saved in my emulator:
void _downloadAndSavePhoto() async { var response = await http.get(Uri.parse(imageUrl)); try { Directory tempDir = await getTemporaryDirectory(); String tempPath = tempDir.path; File file = File('$tempPath/$name.jpeg'); file.writeAsBytesSync(response.bodyBytes); } catch (e) { print(e.toString()); } }
However, when I try the above function for flutter web (using a chrome simulator) I get the following error:
MissingPluginException(No implementation found for method getTemporaryDirectory on channel plugins.flutter.io/path_provider)
I will be more than happy if someone knows a way to do it or have some suggestions to implement that functionality.
Thanks in advance!
-
SULPHURIC ACID about 3 yearsthe solution is stackoverflow.com/questions/49455079/…
-
-
Yunet Luis Ruíz about 3 yearsI think that can probably work. However, I have a list of cards and I need to be able to download the image for each of the cards without opening another window. Can I do that somehow in flutter web?
-
Andrej about 3 yearsDo you have a list of image urls? What does your list of cards look like?
-
Yunet Luis Ruíz about 3 yearsI do not have any code implemented yet. I just want to know if it's possible to do that on flutter web and what could be the best way to achieve that? I have the code that works for IOS and android, but it does not work for flutter web.
-
Andrej about 3 yearsWhat does your code for android and ios look like?
-
Yunet Luis Ruíz about 3 yearsI updated the question, now the code that works for android and IOS have been added
-
Andrej about 3 yearsI edited my answer, tell me if it works for you.