Post form data to server flutter - json

I have been having a lot of trouble sending a post request to a server. It expects a form data type.
This is the error I get after my input.
`image: [The image must be an image.]}}
Most of my data are strings except for an int and a file Image which is selected from gallery by user.
This is my code:
dart code
if(_image!=null){
setState(() {
_isLoading = true;
});
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
var uri = NetworkUtils.host +
AuthUtils.updateSessionRequest;
Map<String, String> data = {"_method": "PATCH",
"first_name": widget.first_name,
"last_name": widget.last_name,
"phone": widget.phone,
"industry":widget.industry,
"country": widget.country,
"state": widget.state,
"fav_quote": widget.fav_quote,
"bio_interest": widget.bio_text,
"terms": "1",
"company": widget.company,
"position": widget.job_position,
"linked_in":widget.linkedin_profile,
"institution": widget.institution,
"degree": widget.degree,
"preference[0]": widget.industry};
String authToken = sharedPreferences.getString("token");
try {
final response = await http.post(
uri,
body: data,
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer ' + authToken,
},
);
final responseJson = json.decode(response.body);
print(responseJson.toString());
if (response.statusCode == 200 || response.statusCode == 201) {
//upload image to server after success response
uploadImage(_image);
NetworkUtils.showToast("Profile successfully update!");
});
} else{
setState(() {
_isLoading = false;
});
NetworkUtils.showSnackBar(_scaffoldKey, 'An error occurred. Please try again');
}
return responseJson;
} catch (exception) {
print(exception.toString());
setState(() {
_isLoading = false;
});
NetworkUtils.showSnackBar(_scaffoldKey, 'An error occurred. Please try again');
}
}
uploadImage(File image) async{
var request = http.MultipartRequest(
"POST",
Uri.parse(NetworkUtils.host +
AuthUtils.endPointUpdateProfile));
request.files.add(await http.MultipartFile.fromPath(
'image',
image.path,
));
try {
var streamedResponse = await request.send();
var response = http.Response.fromStream(streamedResponse);
return response;
} catch (e) {
rethrow;
}
}
}

You need to pass your image like this
request.files.add(await http.MultipartFile.fromPath(
'image',
_image,
));
Here an example how to pass File and String using http
var request = http.MultipartRequest(
"POST",
Uri.parse("http://....."));
request.fields['first_name'] = widget.first_name;
request.fields['last_name'] = widget.last_name;
.....
request.files.add(await http.MultipartFile.fromPath(
'image',
path,
));
try {
var streamedResponse = await request.send();
var response = http.Response.fromStream(streamedResponse);
return response;
} catch (e) {
rethrow;
}

From the above only, with a little modification
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void executePostMethod(String title) async {
var request = http.MultipartRequest("POST", Uri.parse("https://localhost:44377/API/GetStateList"));
request.fields['CountryID'] = "1";
// .....
//request.files.add(await http.MultipartFile.fromPath('image',path,)
//);
// send request to upload image
await request.send().then((response) async {
//print(response);
response.stream.transform(utf8.decoder).listen((value) async {
print(value);
// print("ResponseVal: $value");
if (response.statusCode == 200) {
var imgUploadData = json.decode(value);
print(imgUploadData);
} else {
throw Exception("Faild to Load!");
}
});
}).catchError((e) {
print(e);
});
}

Related

How does the dio package in flutter joins the base-url with url and apikey

How does the dio package in flutter joins the base-url with url and apikey in this code. Iam bit confused with the working of dio package can somebody please help me
If I have a URL of this kind
const req = unirest("GET", "https://tasty.p.rapidapi.com/recipes/list");
"X-RapidAPI-Host": "tasty.p.rapidapi.com",
"X-RapidAPI-Key": "f2c5e7c653mshbc6a7a174c0cda1p1d46c4jsna9d84f0c1681",
"useQueryString": true
Here is an example of making HTTP requests using DIO package:
class Api {
BaseOptions options = BaseOptions(
baseUrl: "your_base_url",
connectTimeout: 30 * 1000,
receiveTimeout: 30 * 1000,
headers: {
'Content-Type': 'application/json',
'X-RapidAPI-Host': 'tasty.p.rapidapi.com',
'X-RapidAPI-Key': '....',
'useQueryString': true
},
);
Dio getDio() {
return Dio(options);
}
Future<dynamic> getRequest(Map<String, String> params) async {
var result;
params['query'] = 'abc'
try {
Dio dio = getDio();
result = await dio.get('/url-path', queryParameters: params);
} on DioError catch (e) {
print(e.toString());
}
if (result != null) {
return result;
}
return null;
}
}

How to pass image file to the body of Http request (POST) in Flutter?

I Took a variable in my State File? image;
Then Accesing image from my device
void filePicker() async {
final File? selectedImage =await ImagePicker.pickImage(source: ImageSource.gallery);
print(selectedImage!.path);
setState(() {
image = selectedImage;
});
}
Then tyring to pass the image file along with other http body parameters. If I didn't pass the image file, then the API didn't show any error. But I need to pass the image file to get the correct result.
As I Explicitly throw Exception, so its throwing exception like Faild to fetch and message in ScaffoldMessenger --> Somthing went wrong
Future<void> SaveCustomTestBooking() async {
var jsonResponse;
if (EncUserId.isNotEmpty) {
var postUri = Uri.parse("http://medbo.digitalicon.in/api/medboapi/SaveCustomTestBooking");
var request = http.MultipartRequest('POST', postUri);
request.fields['VisitDate'] = _selectedDate;
request.fields['EncUserId'] = EncUserId;
request.files.add(new http.MultipartFile.fromBytes('image',await File.fromUri(Uri.parse(image!.path)).readAsBytes(),contentType: new MediaType('image', 'jpeg')));
request.send().then((response) {
if (response.statusCode == 200) {
print("Uploaded!");
Navigator.push(context,MaterialPageRoute(builder: (context) => DieticianAfterDateSelectPage(rresponse:DieticianEncBookingIdModel.fromJson(jsonResponse),)));
} else {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("Somthing went wrong")));
throw Exception("Faild to fetch");
}
});
}
}
You should use MultiPart post method. Take a look at this.
You can pass image file simply in this way:
//header
var headers = {
'content-type': 'multipart/form-data',
'Accept': 'application/json',
};
//setup request
var request = http.MultipartRequest(
"POST", Uri.parse("your api url"));
//add files to reqest body
request.files.add(await http.MultipartFile.fromPath(
'your feild name',
pickedFile.path,
));
//add header
request.headers.addAll(headers);
//send request and return response
try {
var streamedResponse = await request.send();
var response = http.Response.fromStream(streamedResponse);
return response;
} catch (e) {
rethrow;
}
}
Finally managed to slove it using Multipart.. Here is full API function code of mine
Future<void> SaveCustomTestBooking() async {
var jsonResponse;
if (EncUserId.isNotEmpty) {
var response = http.MultipartRequest('POST',Uri.parse("http://myApiTestBooking"));
response.fields['VisitDate'] = _selectedDate;
response.fields['EncUserId'] = EncUserId;
response.fields['Description'] = testTextController.text;
response.files.add(new http.MultipartFile.fromBytes(
"UserFile", File(image!.path).readAsBytesSync(),//UserFile is my JSON key,use your own and "image" is the pic im getting from my gallary
filename:"Image.jpg",
contentType: MediaType('image', 'jpg')));
response.send().then((response) async {
if (response.statusCode == 200){
isApiCallProcess = false;
final respBody = await response.stream.bytesToString();// this is how we print body for Multipart request
jsonResponse = json.decode(respBody.toString());
print(respBody);
print("Uploaded!");
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("Booked"),
backgroundColor: Color(0xFF00b3a4),
));
// Navigator.push(context,new MaterialPageRoute( builder: (context) =>new MyTestReqDetailsPage(),));
Navigator.push(context,new MaterialPageRoute( builder: (context) =>new Home2(),));
}
});
}
}

How can I collect my API data in an Array in flutter?

Basically I want to collect my API data in an array AND add new data to my array every time I'm calling my API, then use map function to construct my dynamic row...I hope you understood my problem.
My code, try to construct dynamic row by collecting data in an Array
Future<void> GetTestFee() async {
var jsonResponse;
if (encTestId.isNotEmpty) {
var response = await http.post(
Uri.parse("http://getrbi.in/api/agtyi/GetTestFee"),
body: ({
'EncPartnerId': encLabId,
'EncTestId': encTestId,
}));
if (response.statusCode == 200) {
print("Correct");
print(response.body);
jsonResponse = json.decode(response.body.toString());
print(jsonResponse);
getTestFeeObj=GetTestFeeMap.fromJson(jsonResponse);
} else {
throw Exception("Faild to fetch");
}
} else {
throw Exception("Faild to fetch");
}
//throw Exception("Faild to fetch");
return GetTestFee();
}
JSON resresponse
{
"EncPartnerId": "LEuT1eIlpLiuiiyAAkZme3wpQ==",
"EncTestId": "U4exk+vfMGrn7cjNUa/kji==",
"Fee": "100",
"DiscountedFee": "80",
"BookingFee": "50"
}
You can add your model to list:
List<GetTestFeeMap> reponseModel =[]
And after getting you response add it into list
var response = await http.post(
Uri.parse("http://ytyttiiiuiu.in/api/medboapi/GetTestFee"),
body: ({
'EncPartnerId': encLabId, // can use for test run "LEuT1eIlpLEMAAkZme3wpQ==",
'EncTestId': encTestId, // "U4exk+vfMGrn7cjNUa/PBw=="
}));
if (response.statusCode == 200) {
print("Correct");
print(response.body);
jsonResponse = json.decode(response.body.toString());
print(jsonResponse);
getTestFeeObj=GetTestFeeMap.fromJson(jsonResponse);
reponseModel.add(getTestFeeObj)
I hope I undrestand right.

Error in fetching data from api in flutter

I have to fetch data from this api - https://api.wazirx.com/api/v2/market-status
I am getting "xmlhttprequest error"
how should I overcome this.
Future<void> fetchUserData() async {
final response = await http.get(Uri.https('api.wazirx.com', '/api/v2/market-status'));
if (response.statusCode == 200) {
print(response.body);
} else {
throw Exception("Request Rejected");
}
}
Try this.
add the headers 'Accept' : 'application/json'
Future<void> fetchUserData() async {
final host = 'api.wazirx.com';
final path = '/api/v2/market-status';
final headers = {'Accept': 'application/json'};
final uri = Uri.https(host, path);
final response = await http.get(uri, headers: headers);
if (response.statusCode == 200) {
print(response.body);
} else {
throw Exception("Request Rejected");
}
}

Flutter | Why does my json file is transformed into a folder on firebase when I try to access it?

When I try to access my json file from my emulator using a url and a http post request in firebase storage, it transorm into a folder, and when I print data, it gives me the data of the folder not the file.
Code:
final _auth = FirebaseAuth.instance;
final _store = Firestore.instance;
String khatma;
String link;
var data;
down_data() async {
final user = await _auth.currentUser();
await _store.collection('users').document(user.uid).get().then(
(value) => {
setState(
() {
khatma = value.data['Joined'];
},
),
},
);
}
Future getAya() async {
await down_data();
if (khatma == 'Khatma 1') {
var response = await http.post(
'https://firebasestorage.googleapis.com/v0/b/khatma-project.appspot.com/o/Ayat%2Fsurah_1.json?alt=media&token=6bc1994b-6896-4541-a20c-687cbe6e6208',
);
data = jsonDecode(response.body);
print(data);
} else if (khatma == 'Khatma 2') {
setState(() {});
} else if (khatma == 'Khatma 3') {
setState(() {});
} else if (khatma == 'Khatma 4') {
setState(() {});
}
}
#override
void initState() {
getAya();
super.initState();
}
What if I nested the Verse_num to name and taken boolean like this:
"Surah_1": {
"verse_1": {
"name": "بِسْمِ ٱللَّهِ ٱلرَّحْمَٰنِ ٱلرَّحِيمِ",
"taken": "true if taken, flase if not"
},
}