upload image with data to server Titanium - http

i have some data i need to upload it to the server with an image using
multipart/form-data
but i getting request time out this is my data
var data={
property_name:p_n_txt.value,
friendly_name:f_txt.value,
property_type:clicked,
size:space_Slider.getValue(),
price:price_Slider.getValue(),
number_of_bedrooms:bedrooms_Slider.getValue(),
number_of_bathrooms:bathrooms_Slider.getValue(),
number_of_parkings:p_space_Slider.getValue(),
location:a_txt.value,
features:13,
payment_method:4,
image1_name:"image0.png",
image1:Ti.Filesystem.getFile(Ti.Filesystem.tempDirectory,Ti.App.Properties.getString("filename")),
};
and the httpclient is
var xhr = Ti.Network.createHTTPClient({
onload: function() {
var myData = JSON.parse(this.responseText);
console.log(this.responseText);
},
// function called when an error occurs, including a timeout
onerror : function(e) {
Ti.API.debug(e.error);
console.log(this.status);
console.log(e.error);
},
timeout : 20000
});
xhr.open('POST','http://url/');
xhr.setRequestHeader("enctype", "multipart/form-data");
xhr.setRequestHeader("Content-Type", "image/png");
// xhr.setRequestHeader("Content-Type", "image/jpeg");
xhr.send(data);
});
here is should form data not a json so there is no need to add json.stringify
but i have 4 cases i tried with them
first :with stringify i got HTTP 415 if i added contentType "image/png"
and HTTP 500 if i didn't added
second without stringify when i add added contentType "image/png" i got request time out
and when i didn't add it i get HTTP 413
any idea on how to accomplish this cause i found many question about it but no one was helpful for me
thanks

Why don't you try with encoding your image as base64encoded and pass it on and at the server end just decode it and you would be go enough to proceed.
Ti.Utils.base64encode(image.toBlob()).toString();
This can be sent to server and no headers would be required to sent.

Related

Why Twilio gives error 400 when image-chart is sended

I'm trying to send images to a whatsapp user via Twilio, but I'm always getting 400 error
(400) Bad Request. -> {"code": 21620, "message": "Media urls: https://image-charts.com/chart?cht=pd&chd=a:10238,10200&chs=400x300&chdls=9e9e9e,10&chco=FFC00C,03A9F4&chtt=Ocupaci%C3%B3n%20en%20almac%C3%A9n&chdl=Contratado%7COcupado&chli=100.37%25&chl=10238%7C10200&chdlp=b&chof=.png are invalid. Please use only valid http and https urls", "more_info": "https://www.twilio.com/docs/errors/21620", "status": 400}
The image works fine in browser or when is send directly to the user directly in whatsapp
I'm encoding the image like this (js):
img_url = encodeURI(img_url);
Any ideas or workaround?
thanks
It seems not every parameter was encoded, example: chd=a:10238,10200 should be chd=a%3A10238%2C10200.
encodeURI won't produce URL safe, you will need to rely on encodeURIComponent but it will encode the whole url ('/chart?' included) so it's not an option either.
If you are doing this server-side from NodeJS:
// node v10+
const url = require('url');
const querystring = require('querystring');
function encode_uri(chart_url) {
const parsed_url = url.parse(chart_url);
// parse the querytring and then encode every parameter values
parsed_url.query = querystring.stringify(querystring.parse(parsed_url.query));
// generate the full url
return url.format({
...parsed_url,
href:undefined,
path:undefined,
search:'?' + parsed_url.query,
});
}
let chart_url = 'https://image-charts.com/chart?cht=pd&chd=a:10238,10200&chs=400x300&chdlp=b&chdls=9e9e9e,10&chco=FFC00C,03A9F4&chtt=Ocupación en almacén&chli=100.37%&chl=10238|10200&chdl=Contratado|Ocupado&chof=.png';
console.log(encode_uri(chart_url));
// Fully encoded URL
// https://image-charts.com/chart?cht=pd&chd=a%3A10238%2C10200&chs=400x300&chdlp=b&chdls=9e9e9e%2C10&chco=FFC00C%2C03A9F4&chtt=Ocupaci%C3%B3n%20en%20almac%C3%A9n&chli=100.37%25&chl=10238%7C10200&chdl=Contratado%7COcupado&chof=.png
If you are doing this on the browser side then use:
function encode_uri(chart_url) {
// use https://developer.mozilla.org/en-US/docs/Web/API/URL
// not supported in IE10
const parsed_url = new URL(chart_url);
// encode every parameter values
[...parsed_url.searchParams.keys()].forEach(key => parsed_url.searchParams.set(key, encodeURIComponent(parsed_url.searchParams.get(key))));
// generate back the full url
return parsed_url.toString();
}
let chart_url = 'https://image-charts.com/chart?cht=pd&chd=a:10238,10200&chs=400x300&chdlp=b&chdls=9e9e9e,10&chco=FFC00C,03A9F4&chtt=Ocupación en almacén&chli=100.37%&chl=10238|10200&chdl=Contratado|Ocupado&chof=.png';
console.log(encode_uri(chart_url));
// https://image-charts.com/chart?cht=pd&chd=a%253A10238%252C10200&chs=400x300&chdlp=b&chdls=9e9e9e%252C10&chco=FFC00C%252C03A9F4&chtt=Ocupaci%25C3%25B3n%2520en%2520almac%25C3%25A9n&chli=100.37%2525&chl=10238%257C10200&chdl=Contratado%257COcupado&chof=.png

angular5 how to make asyc request?

In my project i made multiple request to server to get data for single page. I want to make all request asyc. Right now until i get the response from first request,the response of second request is not load.
So basically i just want to achive asyc request and response so one request will not wait for other request to finish.
Right now it's like first come first serve fashion.
But i want from multiple request which request get first response should load first.
this is code of my component
constructor(private _dashboardService: DashboardService) {
this.getLineChart();
this.todayPaymentDetails();
this.todayPaymentMethod();
this.rewardCustomers();
this.getAverageBill();
this.getItemByVolumn();
this.getItemBySales();
}
todayPaymentMethod(id=null){
this.paymentMethodsLoader=0;
this._dashboardService.getTodayPaymentMethod(id).subscribe(res =>{
if(null != res.data && '' != res.data){
this.location = res.data.location;
this.payment_methods = res.data.payment_methods;
}
this.paymentMethodsLoader=1;
});
}
this is my service code:
getTodayTotalPayment(id) : Observable<any> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.get(environment.apiUrl + constants.API_V1 + 'today-total-payment/'+id, options)
.map(res => res.json())
.catch((error: any) => Observable.throw(error.json().error || error));
}
Here shows code for only one request but as shown in constructor i send multiple request at a time.
FIrst it is not a good practise to call function like this in constructor.
For running multiple request or observable together use operators i.e. switchMap etc.
Follow this video link related to event loop in JavaScript this will improve your JavaScript execution , event loop concepts . also explains how asynchronous code executed.
Hope it will help.

Is there a way to add a post in wordpress via googlescript?

I have a form in googlescript where I can add a user to a sheet.
Is there a way to implement some lines in that code so the script adds a post on a wordpress page?
I read that it's possible via wp_insert_post , but I have no idea how that works in my case.
EDIT:
As Spencer suggested I tried to do it via WP REST API.
The following code seems to be working .............
function httpPostTemplate() {
// URL for target web API
var url = 'http://example.de/wp-json/wp/v2/posts';
// For POST method, API parameters will be sent in the
// HTTP message payload.
// Start with an object containing name / value tuples.
var apiParams = {
// Relevant parameters would go here
'param1' : 'value1',
'param2' : 'value2' // etc.
};
// All 'application/json' content goes as a JSON string.
var payload = JSON.stringify(apiParams);
// Construct `fetch` params object
var params = {
'method': 'POST',
'contentType': 'application/json',
'payload': payload,
'muteHttpExceptions' : true
};
var response = UrlFetchApp.fetch(url, params)
// Check return code embedded in response.
var rc = response.getResponseCode();
var responseText = response.getContentText();
if (rc !== 200) {
// Log HTTP Error
Logger.log("Response (%s) %s",
rc,
responseText );
// Could throw an exception yourself, if appropriate
}
else {
// Successful POST, handle response normally
Logger.log( responseText );
}
}
But I get the error:
[16-09-28 21:24:29:475 CEST] Response (401.0)
{"code":"rest_cannot_create","message":"Sorry, you are not allowed to
create new posts.","data":{"status":401}}
Means: I have to authenticate first.
I installed the plugin: WP REST API - OAuth 1.0a Server
I setup a new user and got a client key and client user.
But from here I have no clue what to do : /
It is possible. Wordpress has a REST API. I can be found at:
http://v2.wp-api.org/
You will use the UrlFetchApp Service to access this api. Documentation can be found at:
https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app
Read the docs and try to write some code. It you get stuck post the code that is confusing you here and I'll update this answer.
You should add you authentification in the header :
var headers = {
... ,
'Authorization' : 'Basic ' + Utilities.base64Encode('USERNAME:PASSWORD'),
};
And then add your header in your parameters :
var params = {
'method': 'POST',
'headers': headers,
'payload': JSON.stringify(payload),
'muteHttpExceptions': true
}
And then use UrlfetchApp.fetch
var response = UrlFetchApp.fetch("https://.../wp-json/wp/v2/posts/", params)
Logger.log(response);
You need to pass the basic auth, like this:
// Construct `fetch` params object
var params = {
'method': 'POST',
'contentType': 'application/json',
'payload': payload,
'muteHttpExceptions' : true,
"headers" : {
"Authorization" : "Basic " + Utilities.base64Encode(username + ":" + password)+"",
"cache-control": "no-cache"
}
};
thank you for giving me these important links.
<3
I installed WP REST API and the OAuth plugin.
In the documentation is written:
Once you have WP API and the OAuth server plugins activated on your
server, you’ll need to create a “client”. This is an identifier for
the application, and includes a “key” and “secret”, both needed to
link to your site.
I couldn't find out how to setup a client?
In my GoogleScriptCode according to the WP API I get the error:
{"code":"rest_cannot_create","message":"Sorry, you are not allowed to create new posts.","data":{"status":401}}
Edit: I found it - it's under User/Application
I'll try to figure it out and get back to you later.

Angular2 : detect error from HTTP post

I cannot interecept error from http post
a part of my mservice (http post method)
addApplicationLink(applicationLink: ApplicationLink){
let body = JSON.stringify(applicationLink);
let requestHeaders = new Headers();
var headers = new Headers();
headers.set('Content-Type', ['application/json; charset=utf-8']);
let reqoptions = new RequestOptions({
headers: headers
});
return this._http.post(this._applicationLinksUrl + this._linkServicePath,body,{headers: headers});
in my component :
addApplicationLink() {
//todo
this.addNewLink = false;
/* check if must be done after call real rest service */
//this.applicationLinks.push(this.applicationLinkAdd);
this._applicationLinkService.addApplicationLink(this.applicationLinkAdd)
.subscribe(data => {
this.applicationLinks.push(this.applicationLinkAdd)
},
error => {
// handle error
console.error('this an erreor ' + error.status)
}
)
When user tries to add two same applicationlinks , the backend returns an error 409
But when I execute , error.status displays 200 in browser console
I see also in browser console
XMLHttpRequest cannot load http://localhost:7001...... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 409.
rem : Http post is made with json , thus there is a prefligth call
Have you an idea to intercept error 409 ?
In fact, your server doesn't send back the CORS header (Access-Control-Allow-Origin' header is missing). This prevent the browser from providing the actual 409 error to the Angular2 application within the browser.
You need to fix first the problem on the server and you will be able to see this 409 error.
For more details about how CORS works, you could have a look at this article:
http://restlet.com/blog/2015/12/15/understanding-and-using-cors/

Download Stream with RestSharp and ResponseWriter

I donwnload a stream with RestSharp by using the ResponseWriter.
var client = new RestClient
var request = new RestRequest();
// ...
request.ResponseWriter = (ms) => {
// how to detect the status code
};
var response = client.Execute(request);
How can I found out the HTTP Status Code in the ResponseWriter?
Is there a better way to download a Stream?
You can check response.StatusCode and response.StatusDescription after executing the request.
Interestingly, if you use the DownloadData method as described here https://github.com/restsharp/RestSharp/wiki/Other-Usage-Examples there is no way to access this information as far as I can tell.
Currently You can use property AdvancedResponseWriter instead ResponseWriter.
The main difference is that AdvancedResponseWriter in addition to Response Stream gets IHttpResponse and You can check Response Status.
It should be working properly from version 106.6.
https://github.com/restsharp/RestSharp/issues/1207

Resources