Connection closed before full header was received on http post in flutter - flutter

I'm trying to do a http post with the picture the user selects, when trying to make the http call, I get the error 'Connection closed before full header was received', I don't know how to fix it, the same error is happening on a real device.
This is also the documentation for the api, the body is form data.
class UploadVideoServices {
static Future<http.StreamedResponse> postProf({
required String imagePath,
required String title,
required bool isPayPerView,
required bool isDeleted,
required bool show,
required List<String> tags,
required String description,
}) async {
var headers = {'Authorization': 'Bearer ${prefs!.getString('token')}'};
var request = http.MultipartRequest(
'POST',
Uri.parse(
"http url/v1/postpic/634d0ebd2be78793c9474ae0/$title/$description/$show/$isPayPerView/$isDeleted/$tags"));
request.fields.addAll({
'file': imagePath,
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
return response;
}
}
=====
using the services
=====
postProf() async {
try {
var result = await UploadVideoServices.postProf(
imagePath: selectedImagePath.value,
title: 'ajanvideo',
isPayPerView: false,
isDeleted: false,
show: true,
tags: ['ajan', 'app'],
description: 'hey',
);
successSnackBar('Done', 'Posted prof');
return result;
} catch (e) {
errorSnackBar('Opps', e.toString());
print(e.toString());
}
}
======
void getImage(ImageSource imageSource) async {
try {
final pickedFile = await ImagePicker().pickImage(source: imageSource);
if (pickedFile != null) {
selectedImagePath.value = pickedFile.path;
}
print(selectedImagePath.value);
await postProf(); // using the method after getting image
} catch (e) {
errorSnackBar('Opps', 'Failed to get image');
}
}

Related

Http listening to upload progress Flutter Web

I was trying to listen to the upload progress using StreamedRequest and wanted to show the upload progress in UI by listening to bytes sent, but for some reason, it doesn't seem to work. The file is being picked with the file picker package and the selected file is in binary format (Unit8List). Here's the code:
final sha1OfFileData = sha1.convert(fileData);
try {
final request = http.StreamedRequest('POST', Uri.parse(data['uploadUrl']));
request.headers.addAll({
'Authorization': data['authorizationToken'],
'Content-Type': "application/octet-stream",
'X-Bz-File-Name': fileName,
'X-Bz-Content-Sha1': sha1OfFileData.toString(),
'X-Bz-Server-Side-Encryption': 'AES256',
});
request.sink.add(fileData);
final streamedResponse = await request.send();
var received = 0;
var total = streamedResponse.contentLength ?? -1;
streamedResponse.stream.listen(
(List<int> chunk) {
received += chunk.length;
if (total == -1) {
print('Received $received bytes');
} else {
final progress = received / total;
print('Upload progress: ${(progress * 100).toStringAsFixed(2)}%');
}
},
onDone: () async {
final responseBytes = await streamedResponse.stream.toBytes();
final responseString = utf8.decode(responseBytes);
response = jsonDecode(responseString);
print(response);
},
onError: (error) {
print('Error uploading file: $error');
},
cancelOnError: true,
);
} catch (e) {
print(e);
}
However if I upload it with the normal request, it works, here's that code:
final sha1OfFileData = sha1.convert(fileData);
var response;
try {
final request = http.Request('POST', Uri.parse(data['uploadUrl']));
request.headers.addAll({
'Authorization': data['authorizationToken'],
'Content-Type': "application/octet-stream",
'X-Bz-File-Name': fileName,
'X-Bz-Content-Sha1': sha1OfFileData.toString(),
'X-Bz-Server-Side-Encryption': 'AES256',
});
request.bodyBytes = fileData;
final streamedResponse = await request.send();
final responseBytes = await streamedResponse.stream.toBytes();
final responseString = utf8.decode(responseBytes);
response = jsonDecode(responseString);
print(response);
} catch (e) {
print(e);
}

client.post login timeout not working in flutter

I need to use timeout if post request not working so, I write below code:
class APIService {
static var client = http.Client();
static Future<bool> login(LoginRequestModel model) async {
Map<String, String> requestHeaders = {
'Content-Type': 'application/json',
};
var url = Uri.http(Config.apiURL, Config.loginAPI);
try {
final response = await client
.post(
url,
headers: requestHeaders,
body: jsonEncode(model.toJson()),
)
.timeout(const Duration(seconds: 5));
print("response:");
print(response);
if (response.statusCode == 200) {
//SHARED
await SharedService.setLoginDetails(loginResponseJson(response.body));
return true;
} else {
return false;
}
} on TimeoutException catch (e) {
// handle timeout
return false;
}
}
But never end await client.post method waiting althouth I add timeout. How can I solve this ?
You can try this:
import 'package:http/http.dart' as http;
import 'package:http/io_client.dart' as http;
final body = { 'email': email, 'password': password };
final client = http.Client();
http.Response res;
try {
res = await client
.post(
url,
headers: requestHeaders,
body: jsonEncode(model.toJson()),
.catchError((e) {
// SocketException would show up here, potentially after the timeout.
})
.timeout(const Duration(seconds: 5));
} on TimeoutException catch (e) {
// Display an alert, no internet
} catch (err) {
print(err);
return null;
}

Image upload using post method in Flutter

I have to upload image from gallery to server using provider in Flutter.
Here is the file picker
_loadPicker(ImageSource source) async {
File picked = await ImagePicker.pickImage(source: ImageSource.gallery);
print(picked);
if (picked != null) {
final response = await Provider.of<ProfilePictureUpdate>(context, listen:
false).profilePicUpdate(picked);
if (response["status"] ) {
Fluttertoast.showToast(msg: response["title"]);
}
else {
Fluttertoast.showToast(msg: response["title"]);
}
}
}
And here is the post method
Future<Map<String, dynamic>> profilePicUpdate(picked) async {
try {
final response = await ApiRequest.send(route: "profile/update/picture", method: "POST",
body: {
" photo_url" : picked,
});
if (response.statusCode == 200 ) {
return {
"status": true,
"title" : response["title"]
};
}
}
If you want sent image to you have to use formData( multi part) in 'Dio' similar
web (enctype). In http, you can also use multipart.
Must remember u use image is always not same, here use this field when server side params name same.
class ImageRepository {
Future<dynamic> uploadImage(filepath) async {
FormData formData = FormData.fromMap({
"image": await MultipartFile.fromFile(filepath,
filename: filepath.split('/').last)
});
var response = await Dio().post(
url,
data: formData),
);
print(response.data);
if (response.statusCode == 200) {
return 'Image Upload';
} else {
throw Exception 'Problem occour';
}
}

fetching the response from API and dealing with the errors / converting Bytestreem to Map in flutter

I am trying to communicate with a PHP backend using API but I can not reach the body of the response.
I got the base code from the postman.
And here is the data of the body response:
I need to reach the message, and the errors to show them in the UI, the problem is response.stream it's type is Bytestreem and I can not convert it to Map
My code:
Future<void> _authenticateUp(String email, String password,
String passwordconfirmation, String username, String name,
{String phonenumber}) async {
var headers = {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
};
var request = http.MultipartRequest('POST', Uri.parse('$siteUrl/register'));
request.fields.addAll({
'email': email,
'password': password,
'password_confirmation': passwordconfirmation,
'username': username,
'name': name,
'phone_number': phonenumber
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
try {
if (response.statusCode == 200) {
await response.stream.bytesToString().then((value) {
print(value);
});
} else {
// here I want to print the message and the errors
}
} catch (e) {
throw e;
}
}
Add this As for Error your statusCode is not 200
try {
if (response.statusCode == 200) {
await response.stream.bytesToString().then((value) {
print(value);
});
} else {
await response.stream.bytesToString().then((value) {
print(value);
var jsonResponse = json.decode(response.body.toString());
var nameError = jsonResponse["errors"]["name"][0];
var emailError = jsonResponse["errors"]["email"][0];
var usernameError = jsonResponse["errors"]["username"][0];
var passwordError = jsonResponse["errors"]["password"][0];
//now can print any print(emailError);
});
}

how to post form data request using flutter in http package

I want to send form data in flutter using the HTTP package. Getting the error:FormatException: Unexpected character (at character 1)
I/flutter (30465):
I am sending the form data in the HTTP post request.
Future<void> authethicate(
String schoolName,
String password,
) async {
try {
final url = 'https://yobimx.com/citykey/api/users/login';
final response = await http.post(url, body: {
'email': 'usamashafiq199#outlook.com',
'password': '123',
}, headers: {
"Content-Type": "application/x-www-form-urlencoded",
});
print(
json.decode(response.body),
);
final responseData = json.decode(response.body);
} catch (error) {
print(error);
}
}
I have to use a multipart request for request. Thanks for your help.
Future<void> authethicate(
String schoolName,
String password,
) async {
try {
final url = Uri.parse('https://yobimx.com/citykey/api/users/login');
Map<String, String> requestBody = <String, String>{
'email': 'usamashafiq199#outlook.com',
'password': '123'
};
var request = http.MultipartRequest('POST', url)
..fields.addAll(requestBody);
var response = await request.send();
final respStr = await response.stream.bytesToString();
print(
jsonDecode(respStr),
);
print("This is the Status Code$respStr");
var encoded = json.decode(respStr);
print(encoded['status']);
print('This is the userId${encoded['data']['user_id']}');
} catch (error) {
print(error);
}
}