如何在 Flutter 中将图像上传到服务器? [英] How to upload images to server in Flutter?

查看:26
本文介绍了如何在 Flutter 中将图像上传到服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想上传一张图片,我正在使用 http.Client() 进行请求,

I would like to upload a image, I am using http.Client() for making requests,

static uploadImage(String id, File file) {
  var httpClient = createHttpClient();

  Map<String, String> headers = new Map<String, String>();
  headers.putIfAbsent("Authorization", () => "---");
  headers.putIfAbsent("Content-Type", () => "application/json");

  var body=new List();
  body.add(id.)
  httpClient.post(URL_UPLOADIMAGE,headers: headers,body: ,encoding: )
}

请求的正文和编码部分应该是什么?

What should be the body and encoding part for the request ?

推荐答案

使用 MultipartRequest

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

命名空间:

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

这篇关于如何在 Flutter 中将图像上传到服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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