【发布时间】:2020-06-04 08:40:41
【问题描述】:
我无法在 Flutter 中使用 http 请求发送空白文件。 服务器给了我例外'500'。 另外我需要发送一个参数“文件名”因为它不是可选的,否则如果文件为空我可以跳过它。
代码如下:
final Uri _saveTaskUrl =
Uri.parse('http://————————);
Future addNewTask(
{File image,
taskName,}) async {
// Intilize the multipart request
final imageUploadRequest = http.MultipartRequest('POST', _saveTaskUrl);
// Attach the file in the request
final mimeTypeData =
lookupMimeType(image?.path ?? '', headerBytes: [0xFF, 0xD8])
.split('/');
//Error is here
//////////////////////////////////////////////////////////
//what to do here if i want to send a blank image file
final file = await http.MultipartFile.fromPath('FileName', image?.path ?? ''
,contentType: MediaType(mimeTypeData[0], mimeTypeData[1]));
////////////////////////////////////////////////////////
imageUploadRequest.files.add( file);
imageUploadRequest.headers.addAll({
"token": centralstate.loginData["AuthToken"],
"clientid": centralstate.loginData["ClientId"].toString(),
});
imageUploadRequest.fields['taskName'] = taskName;
try {
final streamedResponse = await imageUploadRequest.send();
final response = await http.Response.fromStream(streamedResponse);
if (response.statusCode != 200) {
print(
'Error while adding new task : ${response.statusCode} : ${response.body}');
return 0;
}
print(responseData);
return 1;
} catch (e) {
return 0;
}
}
我知道我可以使用 if 语句来检查文件!=null,但我明确想要发送一个空白文件。
【问题讨论】:
-
你试过
MultipartFile.fromBytes构造函数吗,零长度字节数组? -
@RichardHeap 我试过这个:http.MultipartFile.fromBytes('FileName', [], contentType: MediaType(mimeTypeData[0], mimeTypeData[1]));
-
发生了什么?它奏效了吗?您是否使用数据包捕获检查传输的数据。 (如果更容易捕获,您可以在任何机器上使用纯 Dart 项目进行测试。)
-
不,它仍然给我异常 500:发生内部服务器错误。虽然感谢您的建议。由于我找不到任何解决方案,我已经告诉我的 API 开发人员将此参数设为可选。
-
@AnirudhSharma 我也有和你一样的情况,你找到解决办法了吗?