如何从网络下载图像并将其保存在本地目录中? [英] How can I download an image from the network and save it in a locally directory?

查看:21
本文介绍了如何从网络下载图像并将其保存在本地目录中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从网络下载图像,并将其本地保存在计算机的下载文件夹中。我需要为颤动网实现这一点,我不确定如何做到这一点。

我发现了一些关于Android和iOS如何实现文件或镜像下载和保存的问题,例如Flutter save a network image to local directory。我还看了How do I read and write image file locally for Flutter Web?。然而,我看不出这些答案对我有什么帮助。

我认为对于iOS和Ffltter,我可以使用以下函数而不会收到任何错误,但我不知道文件在我的模拟器中保存在哪里:

  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());
    }
  }

但是,当我(使用Chrome模拟器)尝试上面的颤动网函数时,我得到以下错误:

MissingPluginException(No implementation found for method getTemporaryDirectory on channel plugins.flutter.io/path_provider)

如果有人知道实现该功能的方法或有什么建议,我将非常高兴。

提前谢谢!

推荐答案

为此,我建议您首先将universal_html程序包添加到您的pubspec.yaml中,因为在较新版本的Ffltter中,您将收到导入dart:html的警告。

pubspec.yaml中:

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.1 // add http
  universal_html: ^2.0.8 // add universal_html

我创建了一个完全正常工作的颤动Web应用程序示例,您可以尝试它,但您唯一感兴趣的是downloadImage功能。

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,
        ),
      ),
    );
  }
}

这篇关于如何从网络下载图像并将其保存在本地目录中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆