Trying to upload the image to server in the flutte

2019-08-21 08:44发布

问题:

I am new to Flutter development. My problem is that when I try to upload the image to the server I am getting following error:

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

Here is my code:

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

回答1:

In your code you have two different versions of response, with different scopes, which isn't what you intend. Remove the 'var response' and the ; before the body of the 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}");
});


回答2:

It means that response is null. It doesn't have a value. You could try to use a multipart request like in 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
    }

}

thenn call your function with

upload(yourFile);


标签: dart flutter