'How to send a blank file in multipart request
I am unable to send a blank file using http request in flutter. The server is giving me exception '500'. Also I need to send a parameter "Filename" cuz it's not optional, otherwise I can just skip it if file is null.
here's the code:
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;
}
}
from the blank file I mean something like this:
Screenshot from the postman

I know I can use if statement to check file!=null, but I explicitly want to send a blank file.
Solution 1:[1]
http.MultipartRequest request = http.MultipartRequest(
"POST",
Uri.parse(baseUrl + "api/profiles/v1/update/"),
)
..fields['first_name'] = firstName
..fields['last_name'] = lastName
..fields['phone'] = phone
..fields['full_name'] = fullName
..fields['country'] = 'Uzbekistan'
..fields['city'] = 'Tashkent'
..fields['date_birth'] = dateBirth!;
if (req.image == null) {
request.fields['image'] = '';
} else {
var picture = await http.MultipartFile.fromPath(
'image',
req.image!,
filename: req.image!.split('/').last,
);
request.files.add(picture);
}
var response = await request.send();
var responsed = await http.Response.fromStream(response);
print(responsed.body);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DiyorbekDev |
