如何在Flutter中显示来自String Url的图像?

时间:2020-01-05 08:34:34

标签: flutter dart

    FormData formData = FormData.fromMap({
      "image": await MultipartFile.fromFile(image.path,
          filename: "test.${image.path.split(".").last}")
    });

    var dio = Dio();
    var res = await dio.post(
      "$url/users/profile/image/add",
      data: formData),
    );

上面的代码在下面这样返回

{success: true, profile_picture: /files/images/users/40.png}

我要上传'/files/images/users/40.png'时必须使用哪些软件包

2 个答案:

答案 0 :(得分:1)

要从URL下载图像,请使用image_downloader软件包,如下所示:

try {
  // Saved with this method.
  var imageId = await ImageDownloader.downloadImage("https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/flutter.png");
  if (imageId == null) {
    return;
  }

  // Below is a method of obtaining saved image information.
  var fileName = await ImageDownloader.findName(imageId);
  var path = await ImageDownloader.findPath(imageId);
  var size = await ImageDownloader.findByteSize(imageId);
  var mimeType = await ImageDownloader.findMimeType(imageId);
} on PlatformException catch (error) {
  print(error);
}

要将图像上传到服务器,请使用以下代码:

import 'package:path/path.dart';
import 'package:async/async.dart';
import 'dart:io';
import 'package:http/http.dart' as http;

Upload(File imageFile) async {    
    var stream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
      var length = await imageFile.length();

      var uri = Uri.parse(uploadURL);

     var request = new http.MultipartRequest("POST", uri);
      var multipartFile = new http.MultipartFile('file', stream, length,
          filename: basename(imageFile.path));
          //contentType: new MediaType('image', 'png'));

      request.files.add(multipartFile);
      var response = await request.send();
      print(response.statusCode);
      response.stream.transform(utf8.decoder).listen((value) {
        print(value);
      });
    }

You can also refer to this tutorial for learning image upload in Flutter.

要显示来自服务器URL的图像,请使用以下代码:

Image.network(
  imageUrl,
)

此处的imageUrl可以是任何图像网址,例如

https://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png

答案 1 :(得分:0)

要使用其网址显示来自互联网的图像,您可以执行以下操作:

Image.network(
  'https://picsum.photos/250?image=9',
)

要了解更多信息,请click here

相关问题