I am trying to send Form data to the backend using Flutter.
As a result, all the text type data is sent easily but my image file is not shared.
Help me Guys
uploadImage(
filepath,url) async {
EasyLoading.show(status: 'Uploading Data...');
try {
final result = await InternetAddress.lookup('example.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
var request = http.MultipartRequest('POST', Uri.parse(url));
print(filepath); *// this filepath is not empty*
request.files.add(await http.MultipartFile.fromPath('image', filepath));
request.headers.addAll(headers);
request.fields['name'] = _pName.text;
request.fields['store_id'] = store_id;
request.fields['seller_name'] = seller_name;
request.fields['seller_id'] = seller_id;
request.fields['product_id'] = 35.toString();
request.fields['stock_status_id'] = 6.toString();
request.fields['price'] = _pPrice.text;
request.fields['model'] = _pModel.text;
request.fields['sku'] = _pSKU.text;
request.fields['status'] = 1.toString();
request.fields['product_name'] = "Shoes Sport";
request.fields['is_approved'] = 1.toString();
request.fields['special'] = false.toString();
request.fields['quantity'] = _pQuantity.text;
var res = await request.send();
if(res.statusCode==200)
{
EasyLoading.showSuccess('Data is Uploaded!\n Waiting For Approval');
EasyLoading.dismiss();
print(res.reasonPhrase);
Navigator.pop(context);
}
print(request.fields);
// print(filepath);
}
}
on SocketException catch (_) {
EasyLoading.showError("Internet Connection is not available");
}
}
all the data is uploaded except image, i have also crosschecked the parameter its correct.
chek the spelling of "image" it should be same mention in your api doc and the one you are using, your code seems correct i was stuck at the same issue i was using the image key but the key was "profile " please do a recheck , let me know if this works
Related
I want to use to Google places api and
I am trying to call this api but I am getting this. error
Error: XMLHttpRequest error.
static Future<List<Result>?> searchPlaces(context, String query) async {
String mapApiKey = "API_KEY";
String _host = 'https://maps.googleapis.com/maps/api/place/textsearch/json';
final url = '$_host?query=$query&key=$mapApiKey';
//
var response = await http.get(Uri.parse(url));
print(response.body);
//
if (response.statusCode == '200') {
GPlacesSearch result = GPlacesSearch.fromJson(jsonDecode(response.body));
return result.results!;
} else
return null;
}
}
I don't know which platform you are using, but I guess the solution would be to disable chrome web security.
If you are working on mac try the following steps
Go to flutter\bin\cache and remove a file named: flutter_tools.stamp
Go to flutter\packages\flutter_tools\lib\src\web and open the file chrome.dart.
Find '--disable-extensions'
Add '--disable-web-security'
And if you are working on windows just search for how to disable web security for chrome
Use this url 'https://cors-anywhere.herokuapp.com' before your actual url e.g.
String baseUrl = 'https://cors-anywhere.herokuapp.com';
String actualUrl = 'https://maps.googleapis.com/maps/api/place/textsearch/json';
String finalUrl = "$baseUrl/$actualUrl";
static Future<List<Result>?> searchPlaces(context, String query) async {
String mapApiKey = "YOUR_KEY_HERE";
var _sessionToken = Uuid().v4();
String _host =
'https://cors-anywhere.herokuapp.com/https://maps.googleapis.com/maps/api/place/textsearch/json';
final url = '$_host?query=$query&key=$mapApiKey';
//
var response = await http.get(Uri.parse(url);
//
GPlacesSearch result = GPlacesSearch.fromJson(jsonDecode(response.body));
return result.results!;
}
}
How can I get multiple messages from dart isolate?
I'm trying to create an excel file and want to do some operation on that file in an isolate. Before doing an operation on that file, I want to return an message to main isolate, that excel file is created.
Here is function goes in isolate :
foo(String filePath){
// create excel file
var bytes = File(filePath).readAsBytesSync();
var excel = Excel.decodeBytes(bytes);
//HERE I WANT TO SEND THE MESSAGE THAT CREATING EXCEL FILE IS DONE
// some operatoin on excel file
var result = doSomeOperation(excel);
return result;
}
Main isolate code :
var result = await compute(foo, filePath);
What should I do to get creating file message before the actual result comes?
For excel, I'm using excel: ^2.0.0-null-safety-3 package.
Compute only returns one result. If you want to pass multiple 'events' back to the main isolate then you need to use the full Isolate logic (with sendPort and receivePort).
For example, the following code runs in an isolate, and downloads a file while emitting float values to represent progress, potentially a String to indicate log messages and then a bool to indicate success or failure upon completion.
Future<void> isolateDownload(
DownloadRequest request) async {
final sendPort = request.sendPort;
if (sendPort != null) {
var success = false;
var errorMessage = '';
var url = Uri.parse('a_url_based_on_request');
IOSink? out;
try {
http.StreamedResponse response =
await http.Client().send(http.Request('GET', url));
if (response.statusCode == 200) {
var filePath =
join(request.destinationDirPath, '${request.fileName}.ZIP');
var contentLength = response.contentLength;
var bytesLoadedUpdateInterval = (contentLength ?? 0) / 50;
var bytesLoaded = 0;
var bytesLoadedAtLastUpdate = 0;
out = File(filePath).openWrite();
await response.stream.forEach((chunk) {
out?.add(chunk);
bytesLoaded += chunk.length;
// update if enough bytes have passed since last update
if (contentLength != null &&
bytesLoaded - bytesLoadedAtLastUpdate >
bytesLoadedUpdateInterval) {
sendPort.send(bytesLoaded / contentLength);
bytesLoadedAtLastUpdate = bytesLoaded;
}
});
success = true;
if (contentLength != null) {
sendPort.send(1.0); // send 100% downloaded message
}
} else {
errorMessage =
'Download of ${request.fileName} '
'received response ${response.statusCode} - ${response.reasonPhrase}';
}
} catch (e) {
errorMessage = 'Download of ${request.chartType}:${request.chartName} '
'received error $e';
} finally {
await out?.flush();
await out?.close();
if (errorMessage.isNotEmpty) {
sendPort.send(errorMessage);
}
sendPort.send(success);
}
}
}
The code that spawns the isolate then simply checks for the type of the message passed to it to determine the action.
Future<bool> _downloadInBackground(
DownloadRequest request) async {
var receivePort = ReceivePort();
request.sendPort = receivePort.sendPort;
var isDone = Completer();
var success = false;
receivePort.listen((message) {
if (message is double) {
showUpdate(message);
}
if (message is String) {
log.fine(message); // log error messages
}
if (message is bool) {
success = message; // end with success or failure
receivePort.close();
}
}, onDone: () => isDone.complete()); // wraps up
await Isolate.spawn(isolateDownload, request);
await isDone.future;
return success;
}
I have the following method which is use dto verify a ticket/token
var ticketArray = ticket.split('|');
//First check to verify token using simple versification algo
if (widget.eventID.toString() != (ticketArray[0])) {
setState(() {
ticketMainMsg = 'This QR code is NOT VALID';
ticketsubtitle = ticketArray.length != 2
? 'The QR code is fake'
: 'QR code could belong to another event';
ticketStatus = false;
return;
});
}
//Make API call
ticketModel = HttpVerifyTicketPost(
eventId: widget.eventID,
ticket: ticket,
scannerId: widget.scannerId,
).verifyTicket();
}
From above, you can see I do a very simple check on the qr code/token if this simple step fails, I don't bother making an API call and I set the state based on these values.
However if the check passes, then I proceed to make an API call to the server to fully verify the token/code.
My issue is I am struggling to now assign the values from the API call to the ticketStatus, ticketMainMsgand ticketsubtitle parameters. Can anyone helo shed some light. I am quite new to flutter but I am aware that the TicketModel will be a type of Future. My background is PHP so forgive me!
EDIT: The httpVerifyTicket Class
class HttpVerifyTicketPost {
String ticket;
int someId;
int anotherId;
HttpVerifyTicketPost(
{required this.ticket, required this.someId, required this.anotherId});
String verifyURL =
'https://api.com/api/vendors/scanner/native/verify/ticket';
Future<TicketModel> verifyTicket() async {
var storage = await SharedPreferences.getInstance();
var code= storage.getString('code');
var client = http.Client();
var ticketModel = null;
var body = {
'ticket': ticket,
'scanner': scannerCode,
'someId': someId,
'anotherId': anotherId
};
try {
var url = Uri.parse(verifyURL);
var res = await client.post(url, body: jsonEncode(body));
if (res.statusCode == 200) {
var jsonString = res.body;
var jsonMap = json.decode(jsonString);
ticketModel = TicketModel.fromJson(jsonMap);
}
return ticketModel;
} catch (Exception) {
return ticketModel;
}
}
}
Try this please
HttpVerifyTicketPost(
eventId: widget.eventID,
ticket: ticket,
scannerId: widget.scannerId,
).verifyTicket().then((value){setState(() {
ticketModel=value
});
});
I don't quite understand what you want to achieve, but maybe you need to add an asynchronous method like
ticketModel = await HttpVerifyTicketPost( //add await eventId: widget.eventID, ticket: ticket, scannerId: widget.scannerId, ).verifyTicket();
and you must add async like Future Foo() async {your code...}
It Work When String is used BUT Can't fetch String Object.
it Works :-
String? url = "https://api.thedogapi.com/v1/images/search";
var raw = await http.get(Uri.parse(url));
it is Not working :-
getInfoFromSharedPref() async {
dogApiLink = await SharedPreferenceHelper().getDogName();
}
var raw = await http.get(Uri.parse('${dogApiLink}'));
where dogApiLink is String and having Link But Not working.
bro it's direct .. I just don't understand if the return from the shared preferences that you are taking is a link ???? if it's only dog name then that's your problem.. if it's a legitimate link then
{
String uri = "The link";
var response = await http.get(Uri.parse(uri), "The headers of the api").then(){
// The task you wanna perform.
}
}
I am getting the following error when trying to use paypal API
HttpStatusCode: Unauthorized; AUTHENTICATION_FAILURE; Authentication failed due to invalid authentication credentials or a missing Authorization header.
But problem is only when i publish my code to Azure Api. Live store works if I run it on visual studio.
public async Task<bool> InvoicingCreate(Models.ShopTransaction t)
{
sentJson = null;
if (_accessToken == null) await GetAccessTokenAsync();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "v2/invoicing/invoices");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken.access_token);
bool addNotes;
if (t.Product.TotalPrice == 0.0) addNotes = false;
else if (t.PaymentMethod == null) addNotes = true;
else if (t.PaymentMethod == "paypal" || t.PaymentMethod == "credit_card") addNotes = false;
else addNotes = true;
string billingEmail;
if (t.Product.IndividualCouponId.HasValue)
{
billingEmail = _configuration["Shop:CouponInvoiceEmail"];
}
else
{
billingEmail = t.BillingAddress.Email;
}
var inv = new Root
{
detail = new Detail
{
.......details the items. ...
},
.......Fill the items. ...
sentJson = JsonConvert.SerializeObject(inv, Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
request.Content = new StringContent(JsonConvert.SerializeObject(inv), Encoding.UTF8, "application/json");
HttpResponseMessage response = await _httpClient.SendAsync(request);
string content = await response.Content.ReadAsStringAsync();
if (response.StatusCode != System.Net.HttpStatusCode.Created)
{
Error error = JsonConvert.DeserializeObject<Error>(content);
throw new Exception(CompactError("Invoicing-create", response.StatusCode, error));
}
CreateResponse invoiceCreated = JsonConvert.DeserializeObject<CreateResponse>(content);
t.InvoiceId = invoiceCreated.href.Split('/').Last();
return true;
}
Auth methode
appsettings.json paypalmodel
Invoicing methode
I found the problem.
It's an domain issue. It has send to many request on paypal server. So classic denial of service.