尝试使用dart将图像上传到flutter中的服务器

时间:2018-06-28 05:17:08

标签: dart flutter

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

2 个答案:

答案 0 :(得分:0)

这意味着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);

答案 1 :(得分:0)

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

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