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

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

问题描述

我使用网络服务进行图像处理,它在 Postman 中运行良好:

I use a web service for image processing , it works well in Postman:

现在我想用 Dart 发出 http 请求:

Now I want to make http request in flutter with Dart:

import 'package:http/http.dart' as http;

static ocr(File image) async {
    var url = '${API_URL}ocr';
    var bytes = image.readAsBytesSync();

    var response = await http.post(
        url,
        headers:{ "Content-Type":"multipart/form-data" } ,
        body: { "lang":"fas" , "image":bytes},
        encoding: Encoding.getByName("utf-8")
    );

    return response.body;

  }

但我不知道如何上传图像文件,在上面的代码中我得到异常:错误状态:无法设置内容类型为multipart/form-data"的请求的正文字段.
我应该如何编写请求正文?

but I don't know how to upload the image file, in above code I get exception: Bad state: Cannot set the body fields of a Request with content-type "multipart/form-data".
How should I write the body of request?

推荐答案

您的解决方法应该可行;许多服务器将接受 application/x-www-form-urlencoded 作为替代方案(尽管数据的编码效率稍低).

Your workaround should work; many servers will accept application/x-www-form-urlencoded as an alternative (although data is encoded moderately inefficiently).

但是,可以使用 dart:http 来做到这一点.您需要使用 http.MultipartFile 对象,而不是使用 http.post.

However, it is possible to use dart:http to do this. Instead of using http.post, you'll want to use a http.MultipartFile object.

来自 dart 文档:

var request = new http.MultipartRequest("POST", url);
request.fields['user'] = 'someone@somewhere.com';
request.files.add(http.MultipartFile.fromPath(
    'package',
    'build/package.tar.gz',
    contentType: new MediaType('application', 'x-tar'),
));
request.send().then((response) {
  if (response.statusCode == 200) print("Uploaded!");
});

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

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