如何在flutter中上传图像到服务器



如何上传图像到服务器工作在扑动!ImagePicker返回目录的路径,应该发送到服务器的url以及应该使用什么url来显示应用程序上的图像,如果我想在form-data中上传带有授权令牌的png格式,并使用密钥profile_image显示类似的图像。下面是我尝试过的其中一个…

asyncFileUpload(File file) async {
var request = http.MultipartRequest(
"POST",
_getUri(
'/profilepicture',
));
var token = getHeaders();
request.headers["authorization"] = token as String;
;
var pic = await http.MultipartFile.fromPath("profile_image", file.path);
request.files.add(pic);
var response = await request.send();
var responseData = await response.stream.toBytes();
var responseString = String.fromCharCodes(responseData);
print(responseString);
}

您发送到服务器的是.png文件,应该向用户显示的是服务器(url路径)中的图像,而不是来自电话的url路径。因此,如果响应返回那个url,你所需要做的就是在NetworkImage('url')Image.network('url')

中获取它。注意:如果你首先在视图中显示选中的图像,然后有一个按钮提交给服务器,这将是很容易的。如果成功,用服务器

中的url替换图像选取的url
asyncFileUpload(File file) async {
try {
var request = http.MultipartRequest(
'POST',Uri.parse('url'));
var token = getHeaders();
request.headers["authorization"] = token as String;
request.headers.addAll({
'Content-Type': 'application/json'
});
//request.fields.addAll({
// 'user_id': userId,
//});
request.files.add(await http.MultipartFile.fromPath('profile_image',file.path));
var response =  await request.send();
var serverResponse = await http.Response.fromStream(response);
final responseData = json.decode(serverResponse.body);
if(response.statusCode == 200 || response.statusCode == 201){
return responseData;
}else{
return responseData;
}
} catch (e) {
print("Error occurred: $e");
return Future.error(e);
}
}

最新更新