尝试使用飞镖将图像上传到颤振中的服务器



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

这意味着response为空。它没有值。您可以尝试使用多部分请求,如这篇文章所示:

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

在你的代码中,你有两个不同版本的response,具有不同的作用域,这不是你想要的。删除"var 响应"和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}");
});

最新更新