how to do post request if there is multiple image to be sent with other data - flutter

#I am trying to sent my data through rest api all my data seem to be sent accept for my image
static Future<String> postHomework(String classId,String sectionId,String subjectId,String homeWorkTitle,String link,String homeworkDetail, List<XFile> homeworkImage,String submissionDate,BuildContext context) async{
String userData;
String token;
SharedPreferences prefs = await SharedPreferences.getInstance();
userData = prefs.getString("userData");
if(userData!=null){
token = json.decode(userData)['token'];
}else{
return null;
}
http.MultipartRequest request = http.MultipartRequest("POST",Uri.parse("Api goes here"));
Map<String,String> headers = {"Content-Type":"multipart/form-data",'Authorization': 'Bearer $token'};
var bytes = await Future.wait(homeworkImage.map((image) =>image.readAsBytes()));
request.files.addAll(bytes.map((b) =>http.MultipartFile.fromBytes('file', b)));
request.headers.addAll(headers);
request.fields['classid'] = classId;
request.fields['subjectid'] =subjectId;
request.fields['content'] = homeworkDetail;
request.fields['title'] = homeWorkTitle;
request.fields['submission_date'] = submissionDate;
request.fields['section_id'] = sectionId;
http.StreamedResponse responseAttachmentSTR = await request.send();
final reqAttachment = request.files.length;
if(responseAttachmentSTR.statusCode == 200){
print(reqAttachment);
Navigator.of(context).pushNamed("Homework-section-subject-list");
}
print(responseAttachmentSTR.statusCode);
return "SENT";
}
the problem is i am not able to send the images i picked from my gallery to server

Check this out.
I think you have to listen to the response like this :
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});

Related

I create flutter with api call but the data not showing at fresh install

So I create an app with rest API, but the data not showing on a fresh install
This is for gettoken and save to shared prefs
getInit() async {
String myUrl = "$serverUrl/get-token";
http.Response response = await http.post(Uri.parse(myUrl),
body: {'secret': 'code'});
debugPrint(response.statusCode.toString());
debugPrint(response.body);
var data = json.decode(response.body)["data"];
_save(data["access_token"]);
// return data;
}
//SAVE TOKEN
_save(String token) async {
final prefs = await SharedPreferences.getInstance();
const key = 'token';
final value = token;
prefs.setString(key, value);
debugPrint("new token save " + value);
}
This for getlist item, need bearer access token from shared prefs
getRecList() async {
final prefs = await SharedPreferences.getInstance();
const key = 'token';
final value = prefs.get(key) ?? 0;
String myUrl = "$serverUrl/home";
http.Response response = await http.get(Uri.parse(myUrl), headers: {
'Accept': 'application/json',
'Authorization': 'Bearer $value'
});
debugPrint(response.body);
if (response.statusCode == 200) {
List data = jsonDecode(response.body)['data'];
List<ModelKost> modelkost =
data.map((item) => ModelKost.fromJson(item)).toList();
return modelkost;
} else {
return <ModelKost>[];
}
}
So every time I fresh install, home page does not show any data because getRecList item is forbidden access...
The log says token success, but getRecList fails because not get access token, it only happens on fresh install if I refresh/hot reload the list showing normally ...
so I guess the function getRecList wrong here, but I have no idea to fix it ...
i think the problem is you are not waiting for token value. use await when geting value from shared preferences
So I create an app with rest API, but the data not showing on a fresh install
getRecList() async {
final prefs = await SharedPreferences.getInstance();
const key = 'token';
final value =await prefs.get(key) ?? 0; //use await here
String myUrl = "$serverUrl/home";
http.Response response = await http.get(Uri.parse(myUrl), headers: {
'Accept': 'application/json',
'Authorization': 'Bearer $value'
});
debugPrint(response.body);
if (response.statusCode == 200) {
List data = jsonDecode(response.body)['data'];
List<ModelKost> modelkost =
data.map((item) => ModelKost.fromJson(item)).toList();
return modelkost;
} else {
return <ModelKost>[];
}
}

saved token in login page and how to receive it on List page in flutter?

I have two pages,
Login page
list page
Already saved token in login page, but how to receive it on list page inside Future?
Login page response
Future<Album> createAlbum(String employee_custom_id, String password) async {
final response = await http.post(
Uri.parse('https://portal-api.jomakhata.com/api/auth/login'),
headers: <String, String>{
'Content-Type': 'application/json',
},
body: jsonEncode(<String, String>{
'employee_custom_id': employee_custom_id,
'password': password,
}),
);
final data = json.decode(response.body);
if (response.statusCode == 200) {
saveToken(data);
log('$data');
return Album.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to create album.');
}
}
//save token
void saveToken(data) async{
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
sharedPreferences.setString("token", data['token']);
sharedPreferences.setInt("userId", data['userId']);
}
Now i want to received it on list page, but can't set it on token section
**List page **
Future<List<ListAlbum>> listData() async {
final token = // I want to receive token here that i saved in login page.
String url =
'https://portal-api.jomakhata.com/api/getOrganizationData?token=${token}';
Dio dio = new Dio();
dio.options.headers['Content-Type'] = 'application/json';
final body = {'limit': 100, 'orderBy': 'idEmployee', 'orderType': 'DESC'};
final response = await dio.post(url, data: body);
}
If I understand correctly you are asking this
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
final token = sharedPreferences.getString("token");
Wouldn't this make sense?
Future<List<ListAlbum>> listData() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
final token = sharedPreferences.getString("token");
String url =
'https://portal-api.jomakhata.com/api/getOrganizationData?token=${token}';
Dio dio = new Dio();
dio.options.headers['Content-Type'] = 'application/json';
final body = {'limit': 100, 'orderBy': 'idEmployee', 'orderType': 'DESC'};
final response = await dio.post(url, data: body);
}

Image Upload in Flutter Using Http post method

I'm new in this Framework and I want to Upload the Image along with the User name id and wmail and phone,
but Unable to to that I'm getting error
this is the Image get image function
File _image;
final picker = ImagePicker();
Future getImage() async {
pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
} else {
print('No image selected.');
}
});
}
Here i have written the Code for Upkoadung How to do Please help me with that
Future updateUserApiCall(
String name, String email, String mobile, File profile) async {
String token;
var userId;
SharedPreferences storage = await SharedPreferences.getInstance();
token = storage.getString("apiToken");
userId = storage.getInt("id");
String url = "https://www.example.com/api/updateprofile";
final response = await http.post(
url + "?page=" + "",
body: json.encode({
'user_id': userId,
'email': email,
'name': name,
'phone': mobile,
'image': profile,
}),
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer " + token,
},
);
if (response.statusCode == 200) {
print(response.body);
return UpdateProfileResponseModel.fromJson(
json.decode(response.body),
);
} else if (response.statusCode == 400) {
print(response.body);
return ErrorResponseModel.fromJson(
json.decode(response.body),
);
} else if (response.statusCode == 422) {
print(response.body);
return ValidationErrorResponseModel.fromJson(
json.decode(response.body),
);
} else {
print(response);
throw Exception('Failed to load data!');
}
}
}
As far as I know you can not pass image data using just http.post method. You have to use Multipart Request. I have also faced similar problem and asked a similar question in StackOverFlow. Please check the link below:
uploading image using file_picker flutter to a nodejs server
My use case was updating image of an user, I have used the following code to send image to a node server.
Future<bool> updateImage(File imageFile, AuthModel authModel) async{
final String _accessToken = 'abc';
final String url =
'https://justyourserverURL.com/update';
print("auth : " + _accessToken);
var request = http.MultipartRequest('POST', Uri.parse(url));
request.headers['Authorization'] = _accessToken;
// request.fields['id'] = '104';
// request.fields['firstName'] = authModel.data.firstName;
// request.fields['lastName'] = authModel.data.lastName;
// request.fields['surname'] = authModel.data.surname;
request.files.add(await http.MultipartFile.fromPath('file', imageFile.path));
var res = await request.send();
final respStr = await res.stream.bytesToString();
print('responseBody: ' + respStr);
if(res.statusCode==200){
setCurrentUser(respStr);
currentUser = authModelFromJson(respStr);
return true;
} else {
print(respStr);
print('Failed');
return false;
}
}
To pass username or id just pass data using request.fields['user_id'] = userId.

How to Show Snackbar with the Result of Future Http Post?

I'm trying to get a "File was uploaded." string back from a successful Future HTTP post request so that I can create a SnackBar but all I get back from the return is null. Here's the button which calls the Future;
IconButton(
icon: Icon(TriangleAll.upload_3, ),
onPressed: () async {
replyresult = await uploadReply(
filepath: _current.path);
)
if (replyresult != null){
print(replyresult);
}
}
)
And here's the code for the future;
Future<String> uploadReply(
}) async {
final serverurl = "http://example.com/example.php";
final filepath = "examplefilepath";
String serverResponse;
var request = http.MultipartRequest('POST', Uri.parse(serverurl));
var multiPartFile = await http.MultipartFile.fromPath("audio", filepath,
contentType: MediaType("audio", "mp4"));
request.files.add(multiPartFile);
request.send().then((result) async {
http.Response.fromStream(result).then((response) {
if (response.statusCode == 200) {
serverResponse = response.body;
print(serverResponse);
return serverResponse ;
}
});
});
}
I'm trying to use the replyresult variable to create the snackbar upon a successful 200 server response. I know the post is successful as I can see the correct printed serverResponsein the console.
I've tried to simply do;
return response.body ;
But I'm still getting null at the replyresult variable.
because the method returns before the response arrives in Future, do this
var response = await http.Response.fromStream(result);
if (response.statusCode == 200) {
serverResponse = response.body;
print(serverResponse);
return serverResponse ;
} else return '';
or a single await ahead of the Future.
This is what worked.
var multiPartFile = await http.MultipartFile.fromPath("audio", filepath,
contentType: MediaType("audio", "mp4"));
request.files.add(multiPartFile);
final response = await http.Response.fromStream(await request.send());
String serverResponse;
if (response.statusCode == 200) {
String serverResponse = response.body;
print(serverResponse);
return serverResponse;
}

how to upload image to rest API in flutter through http post method?

I'm trying to upload an image through the flutter via post method. and I'm using image_picker for pick file from mobile but I can't able to upload
and I have tried to send the file like FormData that also doesn't work
Future<dynamic> uploadLicence(int id ,dynamic obj) async {
FormData formdata = new FormData(); // just like JS
formdata.add("image",obj);
final response = await post('Logistic/driver/LicenceImage?
driverId=$id',
formdata);
print(response);
// return null;
if (response.statusCode == 200) {
final result = json.decode(response.body);
return result;
} else {
return null;
}
}
after that, I just tried with this method but this also not working
Future<dynamic> uploadLicence(int id, File file) async {
final url = Uri.parse('$BASE_URL/Logistic/driver/LicenceImage?
driverId=$id');
final fileName = path.basename(file.path);
final bytes = await compute(compress, file.readAsBytesSync());
var request = http.MultipartRequest('POST', url)
..files.add(new http.MultipartFile.fromBytes(
'image',bytes,filename: fileName,);
var response = await request.send();
var decoded = await
response.stream.bytesToString().then(json.decode);
if (response.statusCode == HttpStatus.OK) {
print("image uploded $decoded");
} else {
print("image uplod failed ");
}
}
List<int> compress(List<int> bytes) {
var image = img.decodeImage(bytes);
var resize = img.copyResize(image);
return img.encodePng(resize, level: 1);
}
It's possible with MultipartRequest. Or you can use simply dio package. It's one command.
With http:
import 'package:http/http.dart' as http;
final Uri uri = Uri.parse(url);
final http.MultipartRequest request = http.MultipartRequest("POST", uri);
// Additional key-values here
request.fields['sample'] = variable;
// Adding the file, field is the key for file and file is the value
request.files.add(http.MultipartFile.fromBytes(
field, await file.readAsBytes(), filename: filename);
// progress track of uploading process
final http.StreamedResponse response = await request.send();
print('statusCode => ${response.statusCode}');
// checking response data
Map<String, dynamic> data;
await for (String s in response.stream.transform(utf8.decoder)) {
data = jsonDecode(s);
print('data: $data');
}
I user this code for my project i hope work for you
Upload(File imageFile) async {
var stream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
var uri = Uri.parse(uploadURL);
var request = new http.MultipartRequest("POST", uri);
var multipartFile = new http.MultipartFile('file', stream, length,
filename: basename(imageFile.path));
//contentType: new MediaType('image', 'png'));
request.files.add(multipartFile);
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}