【问题标题】:Trying to upload the image to server in the flutter using dart尝试使用飞镖将图像上传到服务器
【发布时间】:2018-12-07 01:55:54
【问题描述】:

我是 Flutter 开发的新手。我的问题是,当我尝试将图像上传到服务器时,出现以下错误:

 NoSuchMethodError: The getter 'body' was called on null.
    Receiver: null
    Tried calling: body

这是我的代码:

var response;
var booking_info_url='http://18.207.188.4/ruralpost/api/api.php?action=booking';
http.post(booking_info_url,body: {"userid":"3","weight":"20","quantity":"1","bimage":base64UrlEncode(await _image.readAsBytesSync())}).then(response);
{
    print("Response body: ${response.body}");
}

【问题讨论】:

  • 您考虑过我对the definite article 的建议吗?它会帮助你写出更精确的问题。
  • 参考This的回答了解如何在flutter中上传图片
  • 已经尝试过@ShyjuMadathil

标签: dart flutter


【解决方案1】:

在您的代码中,您有两个不同版本的response,具有不同的作用域,这不是您想要的。删除 then 正文前的 'var response' 和 ;

String booking_info_url =
    'http://18.207.188.4/ruralpost/api/api.php?action=booking';
http.post(booking_info_url, body: {
  "userid": "3",
  "weight": "20",
  "quantity": "1",
  "bimage": base64UrlEncode(await _image.readAsBytesSync())
}).then((Response response) {
  print("Response body: ${response.body}");
});

【讨论】:

    【解决方案2】:

    表示response 为空。它没有价值。您可以尝试使用像this post 中的多部分请求:

    import 'package:path/path.dart';
    import 'package:async/async.dart';
    import 'dart:io';
    import 'package:http/http.dart' as http;
    
    upload(File imageFile) async {    
        // to byte stream
        var stream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
    
        // get length for http post
        var length = await imageFile.length();
    
        // string to uri
        var uri = Uri.parse("http://18.207.188.4/ruralpost/api/api.php?action=booking");
    
        // new multipart request
        var request = new http.MultipartRequest("POST", uri);
    
        // if you want more data in the request
        request.fields['user'] = 'user001';
    
        var multipartFile = new http.MultipartFile('file', stream, length,
            filename: basename(imageFile.path),
            contentType: new MediaType('image', 'png'));
    
        // add multipart form to request
        request.files.add(multipartFile);
    
        // send request
        var response = await request.send();
    
        if (response.statusCode == "200") {
            // do something on success
        }
    
    }
    

    然后调用你的函数

    upload(yourFile);
    

    【讨论】:

    • 如何传递其他变量
    • @ayubbaba 我将其添加到帖子中。基本上是这样的:request.fields['user'] = 'user001';
    • 对每个要添加的变量使用 request.fields,例如。 request.fields['userid'] = '3'; request.fields['weight'] = '20';
    • 它没有上传
    • 您需要包含更多信息。有没有报错,你检查你真的可以上传到服务器了吗?
    猜你喜欢
    • 2015-01-28
    • 2014-02-07
    • 1970-01-01
    • 2023-03-13
    • 2021-05-08
    • 2013-12-20
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多