SocketException: OS Error: Broken pipe on flutter - flutter

i've been having trouble with video upload.
I'm using Express JS/Node JS as a backend.
The thing is, the upload works when i upload a video of 2 seconds and it works 100% with postman.
but when i try to upload a big video from the app i get :
SocketException: OS Error: Broken pipe, errno = 32, address = 51.254.241.1, port = 47908
and this is my code :
var stream = new http.ByteStream(file.openRead())..cast();
var request = http.MultipartRequest(
"POST",
Uri.parse(sp.getString(SharedPreferencesManager
.LAST_SELECTED_ESTABLISHMENT_ENDPOINT) +
"api/group/uploadVideoFile"));
request.fields["email"] = sp.getString(SharedPreferencesManager.EMAIL);
request.fields["groupId"] = group.id;
request.files.add(http.MultipartFile("video", stream, await file.length(),
filename: file.absolute.path));
// request.files
// .add(http.MultipartFile.fromBytes("video", file.readAsBytesSync()));
// request.files
// .add(await http.MultipartFile.fromPath("video", file.absolute.path));
request.headers.addAll({
"Connection": "keep-alive",
"Accept-Encoding": "gzip,deflate,br",
"Accept": "application/json",
"Authorization": "Bearer " + sp.getString("TOKEN"),
"X-Auth-Token": FlutterConfig.get('X_AUTH_TOKEN')
});
request.send().then((value) => print("jawk behy $value"),
onError: (error) => print("error : $error"));
var response = await request.send();
return json.decode(await response.stream.bytesToString());

Related

Post Files to ASPNetCore API IFormFile Type

I want to send data with files to AspNetCore api that receive files type IFormFile I tried this
Dio dioFile = Dio(
BaseOptions(
baseUrl: baseUrl,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ${APIVariables.token}',
},
),
);
dioFile.post(
url,
data: {
"id": complaint.id,
"title": complaint.title,
"files": complaint.files
.map((file) => base64Encode(file.readAsBytesSync()))
.toList(),
};
);
but it shows dio error: DioError [DioErrorType.response]: Http status error [400].
How can I solve that and is there another better method to do that?
And if I want to send files using MultipartFile how can I do that and what api specialist should do to handle my post?
If you want to send the image file then,
It should look like this.
String fileName = imageFile.path.split('/').last;
FormData formData = FormData.fromMap({
"image-param-name": await MultipartFile.fromFile(
imageFile.path,
filename: fileName,
contentType: new MediaType("image", "jpeg"), //important
),
});
If without this line.
contentType: new MediaType("image", "jpeg")
Maybe it will cause an error: DioError [DioErrorType.RESPONSE]: Http status error [400] Exception
You must confirm the correct contentType to work it as expected
And get MediaType in this package: http_parser

Dio Error : Http Status Error Code [ 405 ] Flutter

I am getting HTTP status error code 405 on sending post requests from the real devices but it's working inside the postman.
The URL is: https://amapp.adtestbed.com/api/post-survey
The following is the form data I am using
FormData formData = FormData.fromMap({
'user_id': id,
'is_collection':
jobDetailsResponseModel.jobData.jobStatus == '8' ? 1 : 0,
'job_id': jobDetailsResponseModel.jobData.id,
'job_no': bookingIdController.text.toString(),
'sender_name': senderNameController.text.toString(),
'reciever_name': recieverNameController.text.toString(),
'sender_phone': senderPhoneController.text.toString(),
'reciever_phone': recieverPhoneController.text.toString(),
'sender_address': senderAddressController.text.toString(),
'reciever_address': recieverAddressController.text.toString(),
'sender_signature_data':
"data:image/jpeg;base64," + base64Imagesendersign,
'receiver_signature_data':
"data:image/jpeg;base64," + base64Imagerecieversign,
'location': currentLocation,
'images[]': uploadimages,
'maked[]': makedlist,
'model[]': modallist,
'rego[]': regolist,
'speedo[]': speedolist,
'is_drivable[]': isdrivablelist,
'goods_inside[]': goodsinsidelist,
'external_condition[]': externalconditionlist,
'interior_condition[]': internalconditionlist,
'survey_image[]': surveyimagelist,
'comments[]': commentlist
});
Here images field is a multipart form list.
And doing requests as follows
final response = await Dio().request(
'https://amapp.adtestbed.com/api/post-survey',
data: formData,
options: Options(
headers: {
"Accept": "application/json",
},
method: 'POST',
),
);
also used the following code to check but still not working
final response = await Dio().post(
'https://amapp.adtestbed.com/api/post-survey',
data: formData,
options: Options(
// headers: {
// // "Accept": "application/json",
// // 'Content-Type': 'application/x-www-form-urlencoded'
// },
method: 'POST',
),
);
When I am sending the form without an images field then it's submitting perfectly and giving 200 status but when I am sending it's with an images field that contains a multipart form list then it's returning 405 status code. End giving the error like the get method not supported only support post method. I also checked the backend code but no error from that's side because it's giving an error before sending the request. I also checked if there were some null data that created errors but not a single field is null.
But when I am doing both cases in postman then it's working fine.
This is the postman link:
https://drive.google.com/file/d/1hTmDC2aQ7vTMxSnzwaeRqd9gv7UbPWhR/view?usp=sharing
These are some images of the postman
https://stackoverflow.com/a/64235806/11623001
Check this out I had a similar issue too before, and I also noticed that you are not adding your authorization token to your header which may explain why you are getting 405 which would mean you can't have access.
I tried to recreate your issue on my end but the authorization token is expired, I'm getting a 401, but here is the code:
void postSome() async {
String base64 =
//This base64 is shortened "data:image/png;base64,...+WZm/et53efvWO6Tuc6rH7kUXy1lxs+/61t7dMg6VAvURAAAAQHMQogDAbE6dlLXtft/F3cuvkJNbetbn7VWrpUUX+mvEtqdHvgAAAABoOf8P3x1uDPELl4UAAAAASUVORK5CYII=";
FormData formData = FormData.fromMap({
'user_id': 139,
'is_collection': "1" == '8' ? 1 : 0,
'job_id': "248",
'job_no': "60036JL#1",
'sender_name': "test",
'reciever_name': "test",
'sender_phone': "1234567890",
'reciever_phone': "1234567890",
'sender_address': "test",
'reciever_address': "test",
'sender_signature_data':
base64,
'receiver_signature_data': base64,
'location': "32, Gopal Nagar, Om Nagar, Gopal Nagar Society, Parvat Patiya, Surat, Gujarat 395010, India\n",
'images[]': "/D:/App/Logicwind/GitLAb/whiteboard-digitization/test_images/w11.jpg",
'maked[]': "test",
'model[]': "test",
'rego[]': "test",
'speedo[]': "123",
'is_drivable[]': "1",
'goods_inside[]': "1",
'external_condition[]': "3",
'interior_condition[]': "3",
'survey_image[]': base64,
'comments[]': "test"
});
final response = await Dio().request(
'https://amapp.adtestbed.com/api/post-survey',
data: formData,
options: Options(
headers: {
'Accept': "application/json",
'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIzIiwianRpIjoiNTlkNzNlZjE4YzcxNGJjMWM1ZjE0ZGQxOWE1OWZmNmQ1YjVhNDViNDIwNzlkODY4ZmJkOGRmNjJlOGM4MDQzNmVjYmIxZjc4MjM5MmZiOGIiLCJpYXQiOjE2MjgxNzY5NTAsIm5iZiI6MTYyODE3Njk1MCwiZXhwIjoxNjU5NzEyOTUwLCJzdWIiOiI0NiIsInNjb3BlcyI6W119.lfnzUvq_LwYtBUQ-t6S_mKXEoM6er6ZzCuTUoHnqz9wwrdLOcu6x9CEixqMRvI-RWtSoiMO5KCYZsgagayGW5slYk6zAAa0V5fCjkRipqqus6mXe6nowtcXs_2V9ucjVoH4Evkb9lFBlE1rlpxKgcGXTcx4UgQs8kjJ5Wm4A8omedza_hUQPN9KUAfhhBDeL9hq-DkC7QbLu_YxnG5g-AETKhbJu8T4HWKqkh9NKGbNlvs1oi_nD81F1w8uSteY-UOgDJyUoGJxzoD6xmEv3J4mkrdr1ZbG88EzTyk3zngwBp9eWcLHhMS2psxArOnOnWusweJJ5uZiWiu2VIL7fWmV5b6G4OCvvkba5eXmw8iAvACACuCGQtOcGdN_euUgyfM9z9a8QbK8M2I-ux4GGY0ejCamFEJZCTwyBCxmLIrP4XjQoeL71WT1YBOgSZwDjA6qrAfL_fLwbEYQYbLIF8fLUmDOWRKBIaJLSVNG2x0Gl5LLXTiTZAzRRtJlSxZ4-Vid4hQJX39lohp-47XPAxvHnNTxiLw_aAG3SruFZ_rtdX4xnNbV3hSI825CD5dBeQC5iE-hiLXDWDXelM_q2fSD1rez62XQZGp1KfvlwowxAWgIghTfSH_E52h6mdoHEo9q73UJNYDz_F9Sj8EOfY3VWtmN6HMmcs4HZht36qX4',
},
method: 'POST',
),
);
print(response.statusCode);
}
It looks like below two fields are files not a form data.
'sender_signature_data': "data:image/jpeg;base64," + base64Imagesendersign
'receiver_signature_data': "data:image/jpeg;base64," + base64Imagerecieversign
You should add those as file fields like this
"sender_signature_data": await MultipartFile.fromFile(sender_signature_path,
filename: fileName, contentType: MediaType(mimee, type))
}),
"receiver_signature_data":await MultipartFile.fromFile(reciever_signature_path,
filename: fileName, contentType: MediaType(mimee, type))
})

Flutter Boundary Regex not accepted

I have to make a post call to upload a image. Getting an error due to the boundary values in the header. (Regex not matched)
var requestUrl = API_URL;
// INITIALIZE MULTIPART REQUEST
http.MultipartRequest request;
// PREPARE HEADER VALUES
request = new http.MultipartRequest("POST", Uri.parse(requestUrl));
Map<String, String> headers = {
'Content-Type': 'multipart/form-data',
'Accept': 'multipart/form-data',
'Authorization': 'Bearer '+accessToken,};
request.headers.addAll(headers);
// DECLARE FILE NAME WEB
String imageType = "image." + this.xfile!.mimeType.toString().split('/').last;
// ADD TO REQUEST
request.files.add(http.MultipartFile.fromBytes('image', await this.xfile!.readAsBytes(), filename:imageType ));
// SEND REQUEST
http.StreamedResponse responseAttachmentSTR = await request.send();
I deployed the codes to the server. Apparently this causes a 403 Forbidden error, when I try to upload an image.
Through debugging, it was because of the regex in the Header (Boundary):
boundary=dart-http-boundary-poYEiL0Ungmxkla.2lkZeC6Mub.-Fupw5T_MmJpxColFVjXf-qr
What can I do about this?

Error http 422 and XMLHttpRequest in flutter

I want to connect to a web service. When I use postman, request send and response receive successfully. But in the flutter app, I get error 422 in the android emulator. And with the same code in flutter web, I get XMLHttpRequest error.
My postman:
This is my data that send to the server:
var data = {
"username": usernameController.text,
"password": passwordController.text,
"email": emailController.text
};
And send a request with dio:
Response response = await client
.post(theUrl,
options: Options(headers: {
HttpHeaders.contentTypeHeader: "application/json",
HttpHeaders.acceptHeader:"*/*"
}),
data: jsonEncode(data))
.timeout(const Duration(seconds: 10));
I get errors on this method:
on DioError catch (error) {
var statusCode = error.response?.statusCode;
print("+++++++++++++++" + statusCode.toString());
print("+++++++++++++++" + error.message);
}
How can I fix these errors?
I Added this code to options in dio and Error 422 in mobile is fixed:
Options(
validateStatus: (status) {
return status! < 500;
},
followRedirects: false,
...)
But I still get error XMLHttpRequest in flutter web.

Http Post is working in Postman, but not Flutter

edit: I found the solution and answered the question.
I'm trying POST to Instagram's API in my app. The POST works fine in Postman, but in my flutter code I always get a error response: {error_type: OAuthException, code: 400, error_message: Invalid platform app} . I must be doing something wrong in my flutter POST but I can't figure out what.
Here is my Postman POST (that works every time) along with the correct body response:
And here is my Dart/Flutter code that gives me the error:
var clientID = '708XXXXXXXX';
var clientSecret = '37520XXXXXXXXXXXXX';
var grantType = 'authorization_code';
var rediUrl = 'https://httpstat.us/200';
var urlTwo = 'https://api.instagram.com/oauth/access_token';
var body = json.encode({
'client_id': clientID,
'client_secret': clientSecret,
'grant_type': grantType,
'redirect_uri': rediUrl,
'code': _accessCode
});
print('Body: $body');
var response = await http.post(urlTwo,
headers: {
'Accept': '*/*',
'Content-Type': 'application/json',
},
body: body,
);
print(json.decode(response.body));
I read about the error on a different thread and they say to post as x-www-formurlencoded.. When I switch the Content-Type to this, I get the same error.
The error I get in Flutter:
{error_type: OAuthException, code: 400, error_message: Invalid platform app}
I triple checked and I am using all the same value in Postman and Flutter. I've tried the values as Strings and numbers.
When I print body:
Body: {"client_id":"70000edited","client_secret":"37520634edited","grant_type":"authorization_code","redirect_uri":"https://httpstat.us/200","code":"AQCs-H3cIU0aF1o2KkltLuTmVMmJ-WJnZIhb9ryMqYedited"}
try this once
final response = await http.post(urlTwo,
body: body,
headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
encoding: Encoding.getByName("utf-8"));
I've finally got it working using a Map. Which is weird because other attempts I also used a map (I've been trying numerous stack overflow answers). Anyways, here is the working code I used:
var urlTwo = 'https://api.instagram.com/oauth/access_token';
var clientID = '7080000';
var clientSecret = '375XXXXXX';
var grantType = 'authorization_code';
var rediUrl = 'https://httpstat.us/200';
var map = new Map<String, dynamic>();
map['client_id'] = clientID;
map['client_secret'] = clientSecret;
map['grant_type'] = grantType;
map['redirect_uri'] = rediUrl;
map['code'] = _accessCode;
http.Response response = await http.post(
urlTwo,
body: map,
);
var respData = json.decode(response.body);
print(respData);