加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

dart – Flutter:http post上传图片

发布时间:2020-12-14 14:55:10 所属栏目:百科 来源:网络整理
导读:我使用Web服务进行图像处理,它在Postman中运行良好: 现在我想用Dart扑灭http请求: 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
我使用Web服务进行图像处理,它在Postman中运行良好:

postman screenshot

现在我想用Dart扑灭http请求:

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”设置Request的正文字段.
我该如何撰写请求正文?

解决方法

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

但是,可以使用dart:http来执行此操作.而不是使用http.post,您将需要使用http.MultipartFile对象.

从dart documentation:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读