Fix the Model Flutter / Dart - php

I have a PHP backend and I use it on my localhost so everything okay but I have a problem that the image URL I get from API is a wrong path and I can't change it from server-side so I decide to fix it on my client-side
I can display an image on my emulator with this path :
http://10.0.2.2:8000/storage/app/public/171/conversions/api-icon.jpg
and the API gives me this path
http://192.168.1.114/multi-restaurants/public/storage/app/public/171/conversions/api-icon.jpg
I fix it by making a function to change the path but it takes a lot of work like I should put this function in every place I wanna display an image!!
I'm sure there is a way to change the path directly from the model when I receive the api
here is my model
class Media {
String id;
String name;
String url;
String thumb;
String icon;
String size;
Media();
Media.fromJSON(Map<String, dynamic> jsonMap)
: id = jsonMap['id'].toString(),
name = jsonMap['name'],
url = jsonMap["url"] ,
thumb = jsonMap['thumb'],
icon = jsonMap['icon'],
size = jsonMap['formated_size'];
This function that I'm using in every class to change path Url
String changepath(String uuu) {
final uri = Uri.parse(uuu);
print("This is $uri");
if (uri.path.contains("multi-restaurants")) {
print("http://10.0.2.2:8000/${uri.pathSegments[2]}/${uri.pathSegments[3]}/${uri.pathSegments[4]}/${uri.pathSegments[5]}/${uri.pathSegments[6]}");
return"http://10.0.2.2:8000/${uri.pathSegments[2]}/${uri.pathSegments[3]}/${uri.pathSegments[4]}/${uri.pathSegments[5]}/${uri.pathSegments[6]}";
}
}
}

If the API constantly sending the URL in "http://192.168.1.114/multi-r ... " in this format, then there is a solution for it, don't know is this a smart move or anything you looking for.Just create String type Function,pass the url from json url = changer(jsonMap["url"]); and use it to convert the URL to desired URL.
String changer(String _string1) {
String _string2 = _string1.replaceAll("http://192.168.1.114/multi-restaurants/public", "http://10.0.2.2:8000");
return _string2;
}

I Solve the Problem with Create a Helper Class and put inside it a static function and call it in every widget I wanna display (Url)
static String changer(String _string1) {
String _string2 = _string1.replaceAll(
"http://192.168.1.114/multi-restaurants/public",
"http://10.0.2.2:8000");
print(_string2);
return _string2;
}

Related

Retrieve facebook user id from the username

I want to retrieve a Facebook user id if I have his username.
This was deprecated from the graph API but I would like to know a work around on getting the id if i have the username.
There is a website that does that but I am not sure how they do it.
I did the R&D and found that the given website is not using the API to fetch userid from the username.
They are using another mechanism which is not valid.
I have found 1 mechanism to find the userid from the username.
Below is the c# code which identify how to find userid from username.
I tried to read the HTML from facebook url. and trying to read below meta tag to identify userid.
META Code
<meta property="al:android:url" content="fb://profile/USERID">
Function
public string findUserIdfromUsername(string facebookURL)
{
try
{
HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load(facebookURL);
List<String> keyLst = doc.DocumentNode
.SelectSingleNode("//meta[#property='al:android:url']")
.Attributes["content"].Value
.Split(',').ToList();
foreach (string strkey in keyLst)
{
string[] arrTemp = strkey.Split('/');
int arrlength = arrTemp.Count();
string facebookUserID = arrlength > 0 ? (arrTemp[arrlength - 1]) : strkey;
facebookUserID = facebookUserID.Replace("?id=", "");
return facebookUserID;
}
}
catch (Exception ex)
{
}
return "";
}
Requirement
I have used "HtmlAgilityPack.dll" to load the html and parse it like XML.
To test call the function like below.
findUserIdfromUsername("https://facebook.com/USERNAME");
I have only test 3-4 urls and getting right userid.
I am not using any API to find USERID.
My English and steps are not too much good. So please manage it.

Accessing main picture of wikipedia page by API

Is there any way I can access the thumbnail picture of any wikipedia page by using an API? I mean the image on the top right side in box. Is there any APIs for that?
You can get the thumbnail of any wikipedia page using prop=pageimages. For example:
http://en.wikipedia.org/w/api.php?action=query&titles=Al-Farabi&prop=pageimages&format=json&pithumbsize=100
And you will get the thumbnail full URL.
http://en.wikipedia.org/w/api.php
Look at prop=images.
It returns an array of image filenames that are used in the parsed page. You then have the option of making another API call to find out the full image URL, e.g.:
action=query&titles=Image:INSERT_EXAMPLE_FILE_NAME_HERE.jpg&prop=imageinfo&iiprop=url
or to calculate the URL via the filename's hash.
Unfortunately, while the array of images returned by prop=images is in the order they are found on the page, the first can not be guaranteed to be the image in the info box because sometimes a page will include an image before the infobox (most of the time icons for metadata about the page: e.g. "this article is locked").
Searching the array of images for the first image that includes the page title is probably the best guess for the infobox image.
This is good way to get the Main Image of a page in wikipedia
http://en.wikipedia.org/w/api.php?action=query&prop=pageimages&format=json&piprop=original&titles=India
Check out the MediaWiki API example for getting the main picture of a wikipedia page: https://www.mediawiki.org/wiki/API:Page_info_in_search_results.
As other's have mentioned, you would use prop=pageimages in your API query.
If you also want the image description, you would use prop=pageimages|pageterms instead in your API query.
You can get the original image using piprop=original. Or you can get a thumbnail image with a specified width/height. For a thumbnail with width/height=600, piprop=thumbnail&pithumbsize=600. If you omit either, the image returned in the API callback will default to a thumbnail with width/height of 50px.
If you are requesting results in JSON format, you should always use formatversion=2 in your API query (i.e., format=json&formatversion=2) because it makes retrieving the image from the query easier.
Original Size Image:
https://en.wikipedia.org/w/api.php?action=query&format=json&formatversion=2&prop=pageimages|pageterms&piprop=original&titles=Albert Einstein
Thumbnail Size (600px width/height) Image:
https://en.wikipedia.org/w/api.php?action=query&format=json&formatversion=2&prop=pageimages|pageterms&piprop=thumbnail&pithumbsize=600&titles=Albert Einstein
Way 1: You can try some query like this:
http://en.wikipedia.org/w/api.php?action=opensearch&limit=5&format=xml&search=italy&namespace=0
in the response, you can see the Image tag.
<Item>
<Text xml:space="preserve">Italy national rugby union team</Text>
<Description xml:space="preserve">
The Italy national rugby union team represent the nation of Italy in the sport of rugby union.
</Description>
<Url xml:space="preserve">
http://en.wikipedia.org/wiki/Italy_national_rugby_union_team
</Url>
<Image source="http://upload.wikimedia.org/wikipedia/en/thumb/4/46/Italy_rugby.png/43px-Italy_rugby.png" width="43" height="50"/>
</Item>
Way 2: use query http://en.wikipedia.org/w/index.php?action=render&title=italy
then you can get a raw html code, you can get the image use something like PHP Simple HTML DOM Parser
http://simplehtmldom.sourceforge.net
I have no time write it to you. just give you some advice, thanks.
I'm sorry for not answering specifically your question about the main image. But here's some code to get a list of all images:
function makeCall($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
return curl_exec($curl);
}
function wikipediaImageUrls($url) {
$imageUrls = array();
$pathComponents = explode('/', parse_url($url, PHP_URL_PATH));
$pageTitle = array_pop($pathComponents);
$imagesQuery = "http://en.wikipedia.org/w/api.php?action=query&titles={$pageTitle}&prop=images&format=json";
$jsonResponse = makeCall($imagesQuery);
$response = json_decode($jsonResponse, true);
$imagesKey = key($response['query']['pages']);
foreach($response['query']['pages'][$imagesKey]['images'] as $imageArray) {
if($imageArray['title'] != 'File:Commons-logo.svg' && $imageArray['title'] != 'File:P vip.svg') {
$title = str_replace('File:', '', $imageArray['title']);
$title = str_replace(' ', '_', $title);
$imageUrlQuery = "http://en.wikipedia.org/w/api.php?action=query&titles=Image:{$title}&prop=imageinfo&iiprop=url&format=json";
$jsonUrlQuery = makeCall($imageUrlQuery);
$urlResponse = json_decode($jsonUrlQuery, true);
$imageKey = key($urlResponse['query']['pages']);
$imageUrls[] = $urlResponse['query']['pages'][$imageKey]['imageinfo'][0]['url'];
}
}
return $imageUrls;
}
print_r(wikipediaImageUrls('http://en.wikipedia.org/wiki/Saturn_%28mythology%29'));
print_r(wikipediaImageUrls('http://en.wikipedia.org/wiki/Hans-Ulrich_Rudel'));
I got this for http://en.wikipedia.org/wiki/Saturn_%28mythology%29:
Array
(
[0] => http://upload.wikimedia.org/wikipedia/commons/1/10/Arch_of_SeptimiusSeverus.jpg
[1] => http://upload.wikimedia.org/wikipedia/commons/8/81/Ivan_Akimov_Saturn_.jpg
[2] => http://upload.wikimedia.org/wikipedia/commons/d/d7/Lucius_Appuleius_Saturninus.jpg
[3] => http://upload.wikimedia.org/wikipedia/commons/2/2c/Polidoro_da_Caravaggio_-_Saturnus-thumb.jpg
[4] => http://upload.wikimedia.org/wikipedia/commons/b/bd/Porta_Maggiore_Alatri.jpg
[5] => http://upload.wikimedia.org/wikipedia/commons/6/6a/She-wolf_suckles_Romulus_and_Remus.jpg
[6] => http://upload.wikimedia.org/wikipedia/commons/4/45/Throne_of_Saturn_Louvre_Ma1662.jpg
)
And for the second URL (http://en.wikipedia.org/wiki/Hans-Ulrich_Rudel):
Array
(
[0] => http://upload.wikimedia.org/wikipedia/commons/e/e9/BmRKEL.jpg
[1] => http://upload.wikimedia.org/wikipedia/commons/3/3f/BmRKELS.jpg
[2] => http://upload.wikimedia.org/wikipedia/commons/2/2c/Bundesarchiv_Bild_101I-655-5976-04%2C_Russland%2C_Sturzkampfbomber_Junkers_Ju_87_G.jpg
[3] => http://upload.wikimedia.org/wikipedia/commons/6/62/Bundeswehr_Kreuz_Black.svg
[4] => http://upload.wikimedia.org/wikipedia/commons/9/99/Flag_of_German_Reich_%281935%E2%80%931945%29.svg
[5] => http://upload.wikimedia.org/wikipedia/en/6/64/HansUlrichRudel.jpeg
[6] => http://upload.wikimedia.org/wikipedia/commons/8/82/Heinkel_He_111_during_the_Battle_of_Britain.jpg
[7] => http://upload.wikimedia.org/wikipedia/commons/6/66/Regulation_WW_II_Underwing_Balkenkreuz.png
)
Note that the URL changed a bit on the 6th element of the second array. It's what #JosephJaber was warning about in his comment above.
Hope this helps someone.
I have written some code that gets main image (full URL) by Wikipedia article title. It's not perfect, but overall I'm very pleased with the results.
The challenge was that when queried for a specific title, Wikipedia returns multiple image filenames (without path). Furthermore, the secondary search (I used the code varatis posted in this thread - thanks!) returns URLs of all images found based on the image filename that was searched, regardless of the original article title. After all this, we may end up with a generic image irrelevant to the search, so we filter those out. The code iterates over filenames and URLs until it finds (hopefully the best) match... a bit complicated, but it works :)
Note on the generic filter: I've been compiling a list of generic image strings for the isGeneric() function, but the list just keeps growing. I am considering maintaining it as a public list - if there is any interest let me know.
Pre:
protected static $baseurl = "http://en.wikipedia.org/w/api.php";
Main function - get image URL from title:
public static function getImageURL($title)
{
$images = self::getImageFilenameObj($title); // returns JSON object
if (!$images) return '';
foreach ($images as $image)
{
// get object of image URL for given filename
$imgjson = self::getFileURLObj($image->title);
// return first image match
foreach ($imgjson as $img)
{
// get URL for image
$url = $img->imageinfo[0]->url;
// no image found
if (!$url) continue;
// filter generic images
if (self::isGeneric($url)) continue;
// match found
return $url;
}
}
// match not found
return '';
}
== The following functions are called by the main function above ==
Get JSON object (filenames) by title:
public static function getImageFilenameObj($title)
{
try // see if page has images
{
// get image file name
$json = json_decode(
self::retrieveInfo(
self::$baseurl . '?action=query&titles=' .
urlencode($title) . '&prop=images&format=json'
))->query->pages;
/** The foreach is only to get around
* the fact that we don't have the id.
*/
foreach ($json as $id) { return $id->images; }
}
catch(exception $e) // no images
{
return NULL;
}
}
Get JSON object (URLs) by filename:
public static function getFileURLObj($filename)
{
try // resolve URL from filename
{
return json_decode(
self::retrieveInfo(
self::$baseurl . '?action=query&titles=' .
urlencode($filename) . '&prop=imageinfo&iiprop=url&format=json'
))->query->pages;
}
catch(exception $e) // no URLs
{
return NULL;
}
}
Filter out generic images:
public static function isGeneric($url)
{
$generic_strings = array(
'_gray.svg',
'icon',
'Commons-logo.svg',
'Ambox',
'Text_document_with_red_question_mark.svg',
'Question_book-new.svg',
'Canadese_kano',
'Wiki_letter_',
'Edit-clear.svg',
'WPanthroponymy',
'Compass_rose_pale',
'Us-actor.svg',
'voting_box',
'Crystal_',
'transportation_inv',
'arrow.svg',
'Quill_and_ink-US.svg',
'Decrease2.svg',
'Rating-',
'template',
'Nuvola_apps_',
'Mergefrom.svg',
'Portal-',
'Translation_to_',
'/School.svg',
'arrow',
'Symbol_',
'stub',
'Unbalanced_scales.svg',
'-logo.',
'P_vip.svg',
'Books-aj.svg_aj_ashton_01.svg',
'Film',
'/Gnome-',
'cap.svg',
'Missing',
'silhouette',
'Star_empty.svg',
'Music_film_clapperboard.svg',
'IPA_Unicode',
'symbol',
'_highlighting_',
'pictogram',
'Red_pog.svg',
'_medal_with_cup',
'_balloon',
'Feature',
'Aiga_'
);
foreach ($generic_strings as $str)
{
if (stripos($url, $str) !== false) return true;
}
return false;
}
Comments welcome.
Lets take Example of Page http://en.wikipedia.org/wiki/index.html?curid=57570
to get Main Pic
Check out
prop=pageprops
action=query&pageids=57570&prop=pageprops&format=json
Results Page Data Eg.
{ "pages" : { "57570":{
"pageid":57570,
"ns":0,
"title":"Sachin Tendulkar",
"pageprops" : {
"defaultsort":"Tendulkar,Sachin",
"page_image":"Sachin_at_Castrol_Golden_Spanner_Awards_(crop).jpg",
"wikibase_item":"Q9488"
}
}
}
}}
We get main Pic file name this result as
** (wikiId).pageprops.page_image = Sachin_at_Castrol_Golden_Spanner_Awards_(crop).jpg**
Now as we have Image file name we will have to make another Api Call to get full image path from file name as follows
action=query&titles=Image:INSERT_EXAMPLE_FILE_NAME_HERE.jpg&prop=imageinfo&iiprop=url
Eg.
action=query&titles=Image:Sachin_at_Castrol_Golden_Spanner_Awards_(crop).jpg&prop=imageinfo&iiprop=url
Returns Array of Image Data having url in it as
http://upload.wikimedia.org/wikipedia/commons/3/35/Sachin_at_Castrol_Golden_Spanner_Awards_%28crop%29.jpg
I there is a way to reliably get a main image for a wikipedia page - the Extension called PageImages
The PageImages extension collects information about images used on a page.
Its aim is to return the single most appropriate thumbnail associated
with an article, attempting to return only meaningful images, e.g. not
those from maintenance templates, stubs or flag icons. Currently it
uses the first non-meaningless image used in the page.
https://www.mediawiki.org/wiki/Extension:PageImages
Just add the prop pageimages to your API Query:
/w/api.php?action=query&prop=pageimages&titles=Somepage&format=xml
This reliably filters out annoying default images and prevents you from having to filter them yourself! The extension is installed on all the main wikipedia pages...
Like Anuraj mentioned, the pageimages parameter is it. Look at the following url that'll bring about some nifty stuff:
https://en.wikipedia.org/w/api.php?action=query&prop=info|extracts|pageimages|images&inprop=url&exsentences=1&titles=india
Her are some interesting parameters:
The two parameters extracts and exsentences gives you a short
description you can use. (exsentences is the number of sentences you want to include in the excerpt)
The info and the inprop=url parameters gives you the url of the page
The prop property has multiple parameters separated by a bar symbol
And if you insert the format=json in there, it is even better
See this related question on an API for Wikipedia. However, I would not know if it is possible to retrieve the thumbnail picture through an API.
You can also consider just parsing the web page to find the image URL, and retrieve the image that way.
Here is my list of XPaths I have found work for 95 percent of articles. the main ones are 1, 2 3 and 4. A lot of articles are not formatted correctly and these would be edge cases:
You can use a DOM parsing lib to fetch image using the XPath.
static NSString *kWikipediaImageXPath2 = #"//*[#id=\"mw-content-text\"]/div[1]/div/table/tr[2]/td/a/img";
static NSString *kWikipediaImageXPath3 = #"//*[#id=\"mw-content-text\"]/div[1]/table/tr[1]/td/a/img";
static NSString *kWikipediaImageXPath1 = #"//*[#id=\"mw-content-text\"]/div[1]/table/tr[2]/td/a/img";
static NSString *kWikipediaImageXPath4 = #"//*[#id=\"mw-content-text\"]/div[2]/table/tr[2]/td/a/img";
static NSString *kWikipediaImageXPath5 = #"//*[#id=\"mw-content-text\"]/div[1]/table/tr[2]/td/p/a/img";
static NSString *kWikipediaImageXPath6 = #"//*[#id=\"mw-content-text\"]/div[1]/table/tr[2]/td/div/div/a/img";
static NSString *kWikipediaImageXPath7 = #"//*[#id=\"mw-content-text\"]/div[1]/table/tr[1]/td/div/div/a/img";
I used a ObjC wrapper called Hpple around libxml2.2 to pull out the image url. Hope this helps
You can also use cocoa Pod called SDWebImage
Code sample (remember to also add import SDWebImage):
func requestInfo(flowerName: String) {
let parameters : [String:String] = [
"format" : "json",
"action" : "query",
"prop" : "extracts|pageimages",//pageimages allows fetch imagePath
"exintro" : "",
"explaintext" : "",
"titles" : flowerName,
"indexpageids" : "",
"redirects" : "1",
"pithumbsize" : "500"//specify image size in px
]
AF.request(wikipediaURL, method: .get, parameters: parameters).responseJSON { (response) in
switch response.result {
case .success(let value):
print("Got the wikipedia info.")
print(response)
let flowerJSON : JSON = JSON(response.value!)
let pageid = flowerJSON["query"]["pageids"][0].stringValue
let flowerDescription = flowerJSON["query"]["pages"][pageid]["extract"].stringValue
let flowerImageURL = flowerJSON["query"]["pages"][pageid]["thumbnail"]["source"].stringValue //fetching Image URL
self.wikiInfoLabel.text = flowerDescription
self.imageView.sd_setImage(with: URL(string : flowerImageURL))//imageView updated with Wiki Image
case .failure(let error):
print(error)
}
}
}
I think not, but you can capture the image using a link parser HTML documents

PHP Error on Code it should not be running

First let me say sorry for the amount of code I'm posting below I'm going to try and keep it as short as possible but this is built on top of my MVC (lightweight-mvc)
Ok So my Problem is that for some reason php is throwing a fatal error on code that should not be being used in my current code,
So how this works I have my MVC witch used the first 2 parts of the url to know what its loading, the problem is I'm building a Moulder CMS into my MVC so it's boot strapping twice,
So here is my Problem,
http://{domain}/admin/control/addon/uploader/method/uploadCheck/
I'm using the above now let me explain a little into that the /admin/control are for the main MVC System it auto-loads the Admin controller then fires the controlAction method from the controller much the same as most MVC's,
The next part are URL paramters that build an array the same as GET or POST would
array('addon'=>'uploader', 'method'=>'uploadCheck')
So from that my control action will auto load as is the code below
public function controlAction(){
global $_URL;
if(cleanData::URL("addon")){
$addonName = "addon_".cleanData::URL("addon");
$methodName = (cleanData::URL("method"))? cleanData::URL("method")."Action" : "indexAction";
echo $methodName;
$addon = new $addonName();
$addon->$methodName();
return;
}else{
$this->loadView("CMS/controll");
}
}
cleanData::URL is an abstract method that just returns the value of the key provided though addSlashes()
So as you can see from the code below it will then use the autoloader to load the module(AKA addon)
Just so you can follow the auto loader works in a simpler version of the Zend Frame work autoloader _ so you have class name addon_admin that would be inside file admin.php that is in the folder addon so the autoloader will load addon/admin.php
So As above with my URL and controlAction it's loading addon/uploader.php and as such this is the contents
<?php
class addon_uploader extends Addons{
public function uploadCheckAction(){
echo 0;
}
public function uploaderAction(){
if (!empty($_FILES)) {
$tmpFile = $_FILES['Filedata']["tmp_name"];
$newLock = "../uploads/".end(explode('/', $tmpFile).$_FILES['Filedata']['name']);
move_uploaded_file($tmpFileName, $newLock);
$POSTback = array(
'name' => $_FILES['Filedata']['name'],
'type' => $_FILES['Filedata']['type'],
'tmp_name' => $newLock,
'error' => $_FILES['Filedata']['error'],
'size' => $_FILES['Filedata']['size']
);
echo json_enocde($POSTback);
}
}
}
?>
But as you can see from my URL its using the uploadCheckAction method witch for debugging i have set so it always says false (AKA 0),
But i seem to get this error:
Fatal error: Only variables can be passed by reference in C:\xampp\htdocs\FallenFate\addon\uploader.php on line 11
But line 11 is $newLock = "../uploads/".end(explode('/', $tmpFile).$_FILES['Filedata']['name']); witch should not be being used could any one provide any help into why this would occur and how i could fix it
end() PHP Manual needs an expression of a single variable (more precisely an array), but not a function return value or any other type of expression.
I think that's basically the cause of your error, more specifically with your code:
$newLock = "../uploads/".end(explode('/', $tmpFile).$_FILES['Filedata']['name']);
you're even driving this far beyond any level of treatment PHP can cope with:
you concatenate an array with a string (which results in a string).
you run end() on that string - not on a variable, not even an array.
I have no clue what you try to do with the code, but I can try:
$filename = $_FILES['Filedata']['name'];
$parts = explode('/', $tmpFile);
$last = end($parts);
$newLock = "../uploads/". $last . $filename;
Or probably even only this:
$filename = $_FILES['Filedata']['name'];
$newLock = "../uploads/". $filename;

How do I POST XML data to a URL via JavaScript in an Adobe AIR app?

I'm writing an application that downloads an XML string from a URL and POSTs that to another URL (that's set up to handle an incoming "XML" field). I've got the first part right - it downloads the XML and I can alert() it and all that, but I'm unable to figure out how to POST that data to a server.
function pull() {
var myLoader = new air.URLLoader();
var myRequest = new air.URLRequest('http://something/something.xml');
myLoader.addEventListener(air.Event.COMPLETE, pulled);
myLoader.load(myRequest);
}
function pulled(evt) {
if (evt.target.bytesTotal>0) {
// alerting shows the full string just fine
alert(evt.target.data);
var myLoader = new air.URLLoader();
var myRequest = new air.URLRequest('http://someplace/push.php');
myRequest.method = air.URLRequestMethod.POST;
// myVars = new air.URLVariables("xml="+evt.target.data); //
// alert(evt.target.data.toUpperCase());
myRequest.data = "xml="+evt.target.data; // myVars;
myLoader.dataFormat = air.URLLoaderDataFormat.TEXT;
myLoader.addEventListener(air.Event.COMPLETE, pushed);
myLoader.load(myRequest);
}
}
I made the 2nd server PHP echo the contents of the xml variable, but I'm just unable to get the exact contents of the XML string. There is something I'm doing wring with the myRequest.data and/or dataFormat bit.
Can someone just figure this out? I know it's probably a simple thing, but I'm at my wit's end right now.
This is my first AIR app.
Another related question (or sub-question) is that...
alert(evt.target.data); // shows an alert box with the XML
alert(typeof evt.target.data); // shows String
alert(evt.target.data.toUpperCase()); // shows the xml converted to upper case
alert(encodeURI(evt.target.data)); // shows up blank.
alert(escape(evt.target.data)); // shows up blank.
Why??
The error seems to be the way you are assigning the parameters to 'data' ... Use URLVariables.
var params:URLVariables = new URLVariables();
params.[name of parameter] = [value];
--- so like params.xml = (YOUR XML) ... from your example:
// uses the dynamic object to add the 'xml' property to 'params' at runtime.
params.xml = evt.target.data
Then Change you request.data to request.data = params;
-- The URLVariables guy is dynamic - so you can add properties as I describe above.
For a basic example - much more complete that what I have here: http://livedocs.adobe.com/flex/3/html/help.html?content=data_access_2.html

Sending ByteArray to Zend_Amf

I'm having problems sending a ByteArray over to my Zend_Amf_server. I get a NetConnection.Bad.Call back from the server. If I send a variable with another datatype then ByteArray it works fine.
I used the same script before with AMFPHP witouth any problems. But for this project I really need this to work in Zend_Amf.
AS3:
var path:String = "/images/picture.jpg";
var ba:ByteArray = jpgencoder.encode(bitmap.bitmapData);
var nc:NetConnection = new NetConnection();
nc.connect(zend_amf_server);
nc.call("Service.saveJPG", new Responder(responseHandler, errorHandler), path, ba);
PHP:
class Service{
public function saveJPG($path, $byteArray){
return "worked";
}
}
I was getting the same error from Zend AMF tonight doing basically the same thing with code that previously worked in AMF. Here's what I have that's working. The only bit I spot different from your code is I'm only passing the ByteArray to Zend, and I'm explicitly setting the ObjectEncoding.
I kept getting empty jpgs on the server because I'd read elsewhere that I needed to do ->data to get to the ByteArray data.
AS3:
_service = new NetConnection();
_service.objectEncoding = ObjectEncoding.AMF3;
_responder = new Responder(this._onSuccess, this._onError);
_service.connect(zend_amf_server);
var myEncoder:JPGEncoder = new JPGEncoder( qualityValue );
var myCapStream:ByteArray = myEncoder.encode ( myBitmapSource ); // myBitmapSource is BitmapData drawn from a Sprite
this._service.call("Remote.savePhotoToServer", this._responder, myCapStream);
PHP:
function savePhotoToServer ( $pInfos )
{
$bytearray = $pInfos;
$idimage = $this->nameImage(".jpg"); // calls a private func for a new name
return ( $success = file_put_contents("./_photos/".$idimage, $bytearray) ) ? $idimage : $success;
}
Thanks David for your reply, the problem seemed to be that I sent a ByteArray to Zend_Amf together with a String.
If I send the ByteArray only it works fine and the Image is saved.
The only problem now is that the path to save the image on should be variable and I can't send it over to my Amf_Server together with the ByteArray at the same time.
Ok, I found the problem. I was using the Zend Framework in the latest 'tag' repository v. 1.7.5 I switched the repository for AMF to the the 'trunk' repository and now it works. There was a bug in Zend_Amf_Server when sending Arrays over to it.

Categories