Invalid request payload input on flutter post request - flutter

I am trying to uploading multiple files from my flutter mobile app. Here is my screenshot of the postman. This works fine on postMan. But I am getting 400 errors on the flutter mobile app. I can't find out where is the problem?
Now here is the code of my flutter mobile app upload.
if(images.length>0){
for (int i = 0; i < images.length; i++) {
var path = await FlutterAbsolutePath.getAbsolutePath(images[i].identifier);
String fileName = path.split('/').last;
var file = await MultipartFile.fromFile(path, filename:fileName);
multipart.add(file);
}
FormData imageFormData = FormData.fromMap(
{
"feedId": value.id,
"images": multipart,
"userInformationsId": value.userInformationId
});
print(multipart.length);
uploadFeedPicture(imageFormData);
}
Future<String> uploadFeedPicture(FormData _imageformData) async{
String at = await _apiProvider.getAccessToken();
Dio dio = new Dio();
// dio.options.headers['accept'] = 'application/json';
// dio.options.headers["content-Type"] = "multipart/form-data";
dio.options.headers["Authorization"] = "Bearer ${at}";
dio.options.baseUrl = getBaseUrl();
var _baseUrl = getBaseUrl();
await dio.post('/api/feed/upload', data: _imageformData, options: Options(
followRedirects: false,
validateStatus: (status) { return status < 500; }
), onSendProgress: (int sent, int total) {
print("$sent $total");
},).then((value) {
print(value.data);
print(value.headers);
}
).catchError((error) => print(error) );
}
And I am getting this response.
{statusCode: 400, error: Bad Request, message: Invalid request payload input}
Please Help me out where is the problem? I try with change content-type but not working.

After trying so many different ways I found the solution. Here it is.
if(value.id != null){
String at = await _apiProvider.getAccessToken();
Map<String, String> headers = { "Authorization": "Bearer ${at}"};
var uri = Uri.parse('$baseUrl/api/feed/upload');
var request = http.MultipartRequest('POST', uri);
request.headers.addAll(headers);
if(images.length>0){
for (int i = 0; i < images.length; i++) {
var path = await FlutterAbsolutePath.getAbsolutePath(images[i].identifier);
// String fileName = path.split('/').last;
var file = await MultipartFile.fromPath("images",path);
request.files.add(file);
}
request..fields['feedId'] = value.id;
request..fields['userInformationsId'] = value.userInformationId;
var response = await request.send();
if (response.statusCode == 200) {
Navigator.pop(context);
showSuccessToast("Posted succesfull");
counter.update(0);
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HomePage()),
);
}else{
showErrorToast("Upload image failed");
}
}
}

Related

Flutter: How to send multiple images using for loop

I am using http package to perform multipart request.I am trying to upload multiple images using for loop but I am not getting any idea how to do it following is my postman response in the below image you can see 2 fields one is attribute and another one is image here I want to loop only adhar and pan inside attributes after sending "mobileno":"4567654","role":"p","userstatus":"D", to database
following is my multipart request code
Future<void> insertCategory(String category, BuildContext context) async {
var flutterFunctions =
Provider.of<FlutterFunctions>(context, listen: false);
var data = {"mobileno":"4567654","role":"p","userstatus":"D","adhar":"adhar","pan":"pan"};
var url = PurohitApi().baseUrl + PurohitApi().insertcategory;
Map<String, String> obj = {"attributes": json.encode(data).toString()};
try {
loading();
final client = RetryClient(
http.Client(),
retries: 4,
when: (reponse) {
return reponse.statusCode == 401 ? true : false;
},
onRetry: (request, response, retryCount) async {
if (retryCount == 0 && response?.statusCode == 401) {
var accesstoken = await Provider.of<Auth>(context, listen: false)
.restoreAccessToken();
request.headers['Authorization'] = accesstoken;
print(accesstoken);
}
},
);
var response = await http.MultipartRequest('Post', Uri.parse(url))
..files.add(await http.MultipartFile.fromPath(
"imagefile", flutterFunctions.imageFile!.path,
contentType: MediaType("image", "jpg")))
..headers['Authorization'] = token!
..fields.addAll(obj);
final send = await client.send(response);
final res = await http.Response.fromStream(send);
var messages = json.decode(res.body);
loading();
print(messages);
} catch (e) {
print(e);
}
}
Future<Object> addUserImages(List<XFile> files, String userID, String token) async {
try {
var url = Uri.parse(API_BASE_URL + addUserImagesUrl);
var request = http.MultipartRequest("POST", url);
request.headers['Authorization'] = "Bearer ${StaticServices.userBaseModel!.token!.token}";
for (var i = 0; i < files.length; i++) {
String fileName = DateTime.now().microsecondsSinceEpoch.toString().characters.takeLast(7).toString();
var pic = http.MultipartFile.fromBytes("files", await File(files[i].path).readAsBytes(), filename: '${userID}_${i}_$fileName', contentType: MediaType("image", files[i].mimeType ?? "png"));
//add multipart to request
request.files.add(pic);
}
var response = await request.send();
var responseData = await response.stream.toBytes();
var responseString = String.fromCharCodes(responseData);
if (response.statusCode == 200) {
return Success(response: Images.fromJson(jsonDecode(responseString)));
}
return Failure(
errorMessage: responseString,
);
} on HttpException {
return Failure(errorMessage: "No Internet Connection");
} on FormatException {
return Failure(errorMessage: "Invalid Format");
} on SocketException {
return Failure(errorMessage: "No Internet Connection");
} catch (e) {
return Failure(errorMessage: "Invalid Error");
}
}

I'm using flutter to update user in Strapi. While running the following code, I am only able to change other fields details but not image. Thank you

I am trying to do so using Multipartfile class. My field name in the strapi is profile_image. Other details are updated, but neither image is uploaded in the media library, nor image is updated for this particular record.
try {
var url = "${kAPIURL}users/${bodyData["id"]}";
var imageBytes = await image!.readAsBytes();
int length = imageBytes.length;
http.ByteStream byteStream = http.ByteStream(image.openRead());
Stream<List<int>> stream = byteStream.cast();
var request = http.MultipartRequest('PUT', Uri.parse(url));
request.headers['Authorization'] = 'Bearer ${bodyData["jwt"]}';
request.fields['id'] = bodyData['id'];
request.fields['username'] = bodyData['username'];
request.fields['specific_type'] = bodyData['specific_type'];
request.fields['sex'] = bodyData['sex'];
request.fields['phone_number'] = bodyData['phone_number'];
request.fields['email'] = bodyData['email'];
var profileImage = http.MultipartFile(
'files.profile_image', stream, length,
filename: image.path.split('/').last.toString(),
contentType: MediaType('image', 'jpg'));
request.files.add(profileImage);
var response = await request.send();
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
if (response.statusCode == 200) {
Provider.of<MainScreenProvider>(context, listen: false).isDeleteCache =
true;
return response;
} else {
return response;
}
} on Exception {
throw Exception("Unable to update user details.");
}

cannot able to send files with extact format in flutter

I'm currently working in a flutter, I'm trying to send a file to the backend server. But I can send a file but the extension is showing as BIN and the file is not supported.
pick() async {
var img = await ImagePicker().getImage(source: ImageSource.gallery);
image = img;
}
send() async {
// if (imageFile == null) {
// return Get.snackbar("alert", 'Please select image');
// }
try {
String? message = messageController.text;
final url = Uri.parse('http://localhost:8000/integration-test');
//Map<String, String> headers = {'Authorization': 'Bearer $token'};
Uint8List data = await this.image.readAsBytes();
List<int> list = data.cast();
var request = http.MultipartRequest('POST', url)
//..headers.addAll(headers)
..fields['sender'] = "venkat"
..fields['numbers'] = numbers
..fields['message'] = message;
if (image != null) {
request.files.add(http.MultipartFile.fromBytes('file', list,
filename: 'example.jpeg'));
}
var response = await request.send();
//var decoded = await response.stream.bytesToString().then(json.decode);
if (response.statusCode == 200) {
Get.snackbar("alert", 'SUCESS');
} else {
Get.snackbar("alert", 'FAILED');
}
} catch (e) {
Get.snackbar('alert', 'Image failed: $e');
}
}
and help to set the file name dynamically.
when i done it with ajax and jquery it works file i need the exact result like this
let formData = new FormData();
let file = $('#1file')[0].files[0];
const sender=c;
const message = $('.i-message').val();
const datepick=$("#i-datetimepicker").val();
formData.append('sender',c);
formData.append('numbers',JSON.stringify(irecepient));
formData.append('message',message);
if(file){
formData.append('file',file);
}
if(datepick){
formData.append('date',datepick);
}
$.ajax({
type: "POST",
url: "http://localhost:8000/integration-test",
//enctype: 'multipart/form-data',
contentType:false,
processData:false,
data: formData,
success: function (data) {
if(data !=0){
$('.logs').append($('<li>').text("task processing"));
}else{
$('.logs').append($('<li>').text("task failed"));
}
}
});
});
this works good and i expect the above flutter code to do this

How to parse a binary data collection (list of files) from multipart/form-data http response?

How to parse a multipart/form-data of http response from server, if it contains a list of binary files (images)?
For example:
var request = http.MultipartRequest('GET', url);
var streamedResponse = await request.send();
if (streamedResponse.statusCode == 200) {
var response = await http.Response.fromStream(streamedResponse); // it is just a binary data, not a list of files
}
Maybe there is something similar to HttpMultipartParser from .NET in flutter?
Try below solution
Future uploadmultipleimage(List images) async {
var uri = Uri.parse("");
http.MultipartRequest request = new http.MultipartRequest('POST', uri);
request.headers[''] = '';
request.fields['user_id'] = '10';
request.fields['post_details'] = 'dfsfdsfsd';
//multipartFile = new http.MultipartFile("imagefile", stream, length, filename: basename(imageFile.path));
List<MultipartFile> newList = new List<MultipartFile>();
for (int i = 0; i < images.length; i++) {
File imageFile = File(images[i].toString());
var stream =
new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
var multipartFile = new http.MultipartFile("imagefile", stream, length,
filename: basename(imageFile.path));
newList.add(multipartFile);
}
request.files.addAll(newList);
var response = await request.send();
if (response.statusCode == 200) {
print("Image Uploaded");
} else {
print("Upload Failed");
}
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}

http MultipartRequest file not receiving in server

I'm trying to upload image to my server but it's not receiving in my server when I upload file from app. But if I upload via postman it works but not from simulator
My Code
final request = http.MultipartRequest(
'POST', Uri.parse(''));
request.fields['title'] = title.text;
request.fields['sub_title'] = subTitle.text;
request.files
.add(await http.MultipartFile.fromPath('profile_photo', photo.path));
request.files
.add(await http.MultipartFile.fromPath('profile_video', video.path));
var response = await request.send();
var responseString = await response.stream.bytesToString();
print(responseString);
`
Output
{'title': 'zia', 'sub_title' : 'sultan', 'profile_photo' : {}, 'profile_video' : {}}
I too faced a similar issue and here is the solution to how I fixed it:
var fileExtension = AppUtils.getFileExtension(filePath);
if (fileExtension.isEmpty) {
AppUtils.showToast('File extension was not found');
return false;
}
final file = await http.MultipartFile.fromPath('vid', filePath,
contentType: MediaType('application', fileExtension));
request.files.add(file);
var res = await request.send();
if (res.statusCode == 200) {
final respString = await res.stream.bytesToString();
debugPrint('respString: $respString');
}
AppUtils:
class AppUtils {
static String getFileExtension(String filePath) {
try {
int index = filePath.lastIndexOf('.');
return filePath.substring(index + 1);
} catch (e) {
return '';
}
}
}