Abi*_*san 6 api http multipart flutter
我想通过多部分文件请求上传图像。使用此代码当我传递两个图像文件时,它工作正常。但是,当我想传递一个图像文件而另一个图像文件为空时,它就不起作用。哪里有问题?我该如何解决这个问题?
这是我的代码 -
Future<Map<String, dynamic>> updateprofile(
UpdateProfileInfo updateProfileInfo,
File imageFile,
File signatureFile) async {
String url = "$baseAPIUrl/update-profile-info";
String _token = await SavedData().loadToken();
String authorization = "Bearer $_token";
final headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
"Authorization": authorization
};
var request = http.MultipartRequest("POST", Uri.parse(url));
request.headers.addAll(headers);
request.fields.addAll(updateProfileInfo.toJson());
request.files
.add(await http.MultipartFile.fromPath('image', imageFile.path));
request.files.add(
await http.MultipartFile.fromPath('signature', signatureFile.path));
print(" Update Profile Json ${updateProfileInfo.toJson()}");
print("Request Fields ${request.fields}");
http.StreamedResponse response = await request.send();
String respStr = await response.stream.bytesToString();
dynamic respJson;
try {
respJson = jsonDecode(respStr);
} on FormatException catch (e) {
print(e.toString());
}
print('API ${response.statusCode}\n $respJson');
bool isSuccess = response.statusCode == 200;
var data = json.decode(respStr);
return {
'isSuccess': isSuccess,
"message": isSuccess ? data["success"]["message"] : null,
"name": isSuccess ? data["success"]["name"] : null,
"classgroup": isSuccess ? data["success"]["classgroup"] : null,
"image": isSuccess ? data["success"]["image"] : null,
"error": isSuccess ? null : data['error']['message'],
};
}
Run Code Online (Sandbox Code Playgroud)
这是邮递员截图
1.
2. POSTMAN 为 Dart 生成的代码 - http
当您的文件之一为空时,您应该避免将其添加到请求正文中。
if(imageFile != null){
request.files
.add(await http.MultipartFile.fromPath('image', imageFile.path));
}
if(signatureFile != null){
request.files.add(
await http.MultipartFile.fromPath('signature', signatureFile.path));
}
Run Code Online (Sandbox Code Playgroud)
这是因为signatureFile.path会在这里导致错误
| 归档时间: |
|
| 查看次数: |
8314 次 |
| 最近记录: |