I am working on a mobile android project that uploads images to the server. I am doing it in Flash Builder with the help of the PHP scripts on the server. My web page is hosted by goDaddy and I have done the permissions for uploading files as; I can upload image through web page. However, when I am trying to send from application it does not upload. Any ideas about the problem? My code is as below;
Flash Builder:
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
title="Photo Upload">
<fx:Script>
<![CDATA[
private var urlRequest:URLRequest = new URLRequest("http://www.mywebsite.com/upload_file.php");
private var file:File;
//take a new picture with the camera
//select a picture from the camera roll (gallery)
protected function uploadGallery_clickHandler(event:MouseEvent):void
{
if (CameraRoll.supportsBrowseForImage)
{
trace("camera roll is supported");
var roll:CameraRoll = new CameraRoll();
roll.browseForImage();
roll.addEventListener(MediaEvent.SELECT,selectCompleteHandler);
}
else
{
trace("camera roll not supported");
statusText.text = "Camera roll not supported on this device.";
}
}
//when the selection is complete upload it
protected function selectCompleteHandler(event:MediaEvent):void
{
trace("event.data.file.url; = "+event.data.file.url);
file = event.data.file;
file.addEventListener(Event.COMPLETE,uploadCompleteHandler);
file.addEventListener(Event.OPEN,openUploadHandler);
file.upload(urlRequest);
}
protected function uploadCompleteHandler(event:Event):void
{
trace("upload complete");
statusText.text = "Photo Uploaded";
}
protected function openUploadHandler(event:Event):void
{
trace("uploading");
statusText.text = "Uploading...";
}
]]>
</fx:Script>
<s:VGroup x="21" y="23" width="200" height="200">
<s:Label id="statusText" fontSize="24" text="Choose a Photo..."/>
<s:Button id="galleryPhotoButton" label="Upload from Gallery"
click="uploadGallery_clickHandler(event)"/>
</s:VGroup>
</s:View>
PHP script on the server:
<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
Do you get any error or any exception on the execution of above code ?
Also you can try adding the urlRequest method as follows to see if it works :
urlRequest.method = URLRequestMethod.POST;
Related
I have a problem when attempting to use Fuel to send image to my server.
I am trying to use the Fuel.upload method.
Fuel.upload(urlfile).source { request, url ->
File(photopath)
}.responseString { request, response, result ->
}
the image is like : /storage/emulated/0/Android/data/fr.tais.riodi/files/Pictures/MyPicture4945313277123614993.jpg
$target_dir = "images/";
$target_file_name = $target_dir .basename($_FILES["file"]["name"]);
$response = array();
// Check if image file is a actual image or fake image
if (isset($_FILES["file"]))
{
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file_name))
{
$success = true;
$message = "Successfully Uploaded";
}
else
{
$success = false;
$message = "Error while uploading";
}
}
else
{
$success = false;
$message = "Required Field Missing";
}
$response["success"] = $success;
$response["message"] = $message;
echo json_encode($response);
I tried to find an example of this operation. Have you an examples or an idea?
Thanks all
I have a very hard problem :-(
I try to deploy an Android App based on Ionic and Cordova. The App takes a picture and upload it to a server, sounds easy.
BUT on Blackberrys Z10 Android I got a Problem creating the Blob for Uploading :-(
Code Snippets
var imgBlob = $helper.createBlob(this.result, "image/jpeg");
var fd = new FormData();
fd.append('photo', imgBlob, file.name);
fd.append('attachedData', attachedData);
BaasBox.uploadFile(fd).done(function (result) {}
$helper.createBlob is like
self.createBlob = function(data, datatype)
{
var out;
try {
out = new Blob([data], {type: datatype});
console.debug("case 1");
}
catch (e) {
window.BlobBuilder = window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder;
if (e.name == 'TypeError' && window.BlobBuilder) {
var bb = new BlobBuilder();
bb.append(data);
out = bb.getBlob(datatype);
console.debug("case 2");
}
else if (e.name == "InvalidStateError") {
// InvalidStateError (tested on FF13 WinXP)
out = new Blob([data], {type: datatype});
console.debug("case 3");
}
else {
// We're screwed, blob constructor unsupported entirely
console.debug("Errore");
}
}
return out;
}
I have no idea how I can solve this ... :-(
regards
Meex
I developing an Android application using Titanium Appcelerator. I had tried to Post text and Image via facebook feed dialog
.. But error while load my local image URL..
var fileimg = Titanium.Filesystem.getFile(backupDir.nativePath, "myimg.jpg");
var fb_data1 = {
description : "Some good text",
picture : fileimg.nativePath,
link : "www.googlee.com",
};
facebook_qfav.dialog("feed", fb_data1, showRequestResult);
function showRequestResult(e) {
var s = '';
if (e.success) {
s = "SUCCESS";
if (e.result) {
s += "; " + e.result;
}
if (e.data) {
s += "; " + e.data;
}
if (!e.result && !e.data) {
s = '"success",but no data from FB.I am guessing you cancelled the dialog.';
}
} else if (e.cancelled) {
s = "CANCELLED";
} else {
s = "FAILED ";
if (e.error) {
s += "; " + e.error;
alert("facebook Share " + s);
}
}
}
ERROR: "Image URL not properly formatted"
File path will be like this: file:///storage/sdcard0/myimg.jpg
But if i pass the remote URL to the picture property , the image is shown in the dialog...
what happens to the local URL..?
I think the only issue is that nativepath has capital P in it. so, its : nativePath
so instead of picture : fileimg.nativepath, It Should be picture : fileimg.nativePath,
Documentation.
Hope it helps.
I tried several ways to upload a file on the FTP server, but I failed in that.
Here I am pasting My server code (php)to accept the file from the device, please provide android code corresponding to that server code.
<?php
error_reporting(0);
include("dbconfig.php");
$msg = '';
$status = 1;
$overwrite = 1;
/*echo "<pre>";
print_r($_POST);
echo "</pre>";*/
/*echo "<pre>";
print_r($_FILES);
echo "</pre>";*/
if(trim($_POST['userid'])!='')
{
$userid = trim($_POST['userid']);
$overwrite = trim($_POST['overwrite']);
if($overwrite == 0)
{
$selfilesqry = mysql_query("SELECT filepath FROM userfiles WHERE userid = 1 AND status=1");
while($row = mysql_fetch_array($selfilesqry))
{
$selfiles[] = $row['filepath'];
}
}
/* echo "<pre>";
print_r($selfiles);
echo "</pre>";*/
$host = '97.***.****';
$usr = '*****************8';
$pwd = '**********************';
$paths = '/mobbisys/cloudbin/data';
//$paths = '/php_projects/mahesh/ftpupload/data';
// connect to FTP server (port 21)
$conn_id = ftp_connect($host, 21) or die ("Cannot connect to host");
// send access parameters
ftp_login($conn_id, $usr, $pwd) or die("Cannot login");
for($i=0; $i<count($_FILES['txtfile']['name']); $i++)
{
if($_FILES['txtfile']['name'][$i]!='')
{
$type = explode('/',$_FILES['txtfile']['type'][$i]);
$filetype = $type[0];
if($filetype == 'audio')
{
$path = $paths."/audio";
}
else if($filetype == 'video')
{
$path = $paths."/video";
}
else if($filetype == 'image')
{
$path = $paths."/image";
}
else
{
$path = $paths."/misc";
}
//echo "<br />".$path;
$name = $_FILES['txtfile']['name'][$i];
$filep = $_FILES['txtfile']['tmp_name'][$i];
// turn on passive mode transfers (some servers need this)
// ftp_pasv ($conn_id, true);
$filepath = strtolower($path.'/'.$name);
if($overwrite == 1)
{
// perform file upload
$upload = ftp_put($conn_id, $path.'/'.$name, $filep, FTP_BINARY);
// check upload status:
if(!$upload)
{
$msg .= '<br />Cannot upload - '.$_FILES['txtfile']['name'][$i];
}
else
{
$msg .= '<br />Upload complete - '.$_FILES['txtfile']['name'][$i];
$sqlAdd = "INSERT INTO userfiles(userid, filetype, filepath, createddate, modifieddate, status) VALUES(".$userid.",'".$filetype."','".$filepath."',NOW(),NOW(),'".$status."') ";
$resAdd = mysql_query($sqlAdd);
}
}
else
{
if(in_array($filepath, $selfiles))
{
$msg .= '<br />Cannot upload - '.$_FILES['txtfile']['name'][$i].' already exist.';
}
else
{
// perform file upload
$upload = ftp_put($conn_id, $path.'/'.$name, $filep, FTP_BINARY);
// check upload status:
if(!$upload)
{
$msg .= '<br />Cannot upload - '.$_FILES['txtfile']['name'][$i];
}
else
{
$msg .= '<br />Upload complete - '.$_FILES['txtfile']['name'][$i];
$sqlAdd = "INSERT INTO userfiles(userid, filetype, filepath, createddate, modifieddate, status) VALUES(".$userid.",'".$filetype."','".$filepath."',NOW(),NOW(),'".$status."') ";
$resAdd = mysql_query($sqlAdd);
}
}
}
}
}
// close the FTP stream
ftp_close($conn_id);
}
else
{
$msg = 'Please provide userid';
}
echo $msg;
?>
You have to include move_uploaded_file function when you want insert
Syntax : move_uploaded_file ( string $filename , string $destination )
Example : move_uploaded_file($_FILES['uploadedfile']['tmp_name'], "./upload/".$_FILES["uploadedfile"]["name"]);
http://php.net/manual/en/function.move-uploaded-file.php
this is bad code. why not upload the files from android device via ftp without a server side script?
see here
we're programming a little "home device control" app within our studying using Appcelerator Titanium. We programmed a back-end in Java which is connected to our front-end apps with an interface which can receipt requests through a SOAP call. Therefore we used the suds.js. All works fine with iOS but nothing seems to happen in Android and we do not know why. :-(
First of all we want to provide a user-login to authorize the user. Name and password will be send to the back-end which provides a user-token afterwards. In iOS all works fine, Android seems to have a problem with the following code which I noticed through different test comments because the comments within this code are not shown in the developer console:
suds.invoke('login', callparams, function(xmlDoc) {
Titanium.API.info("Test after function is called");
var results = xmlDoc.documentElement.getElementsByTagName('return');
Titanium.API.info("another test comment");
Titanium.API.info(results);
if (results && results.length>0) {
var isAdmin = results.item(0).getElementsByTagName('admin');
if(isAdmin.item(0).text == "true") {
Titanium.API.info("isAdmin: true");
Titanium.App.Properties.setBool('isAdmin', true);
} else {
Titanium.API.info("isAdmin: false");
Titanium.App.Properties.setBool('isAdmin', false);
}
var userToken = results.item(0).getElementsByTagName('userToken');
Titanium.API.info("userToken: " + userToken.item(0).text);
Titanium.App.Properties.setString('userToken', userToken.item(0).text);
Titanium.App.Properties.setString('username', username.value);
//Rein oder raus???
//alert("Login erfolgreich! \n isAdmin: " + isAdmin.item(0).text + " \n userToken: " + userToken.item(0).text)
//Aufruf Hauptmenüfenster
openWindow('js/menue.js', 'Hauptmenü', true);
} else {
var resultsError = xmlDoc.documentElement.getElementsByTagName('S:Fault');
var errorString = resultsError.item(0).getElementsByTagName('faultstring');
Titanium.API.info("error: " + errorString.item(0).text);
alert(errorString.item(0).text);
}
});
The url-link to the back-end: http://localhost:8888 Localhost because the back-end is running on my desktop for testing. I am not sure if the request will be receipt of the back-end at all.
Thanks for help in advance!
Best regards, Stefan
The whole code:
Part of app.js: (sorry for german code comments)
// Checkbox bekommt Eventlistener, der Angibt ob das Passwort gespeichert werden soll.
checkbox.addEventListener('click', function(e) {
if(Titanium.App.Properties.getBool('loginAuto') == true){
imageUrl = 'images/checkbox_unchecked.png';
Titanium.App.Properties.setBool('loginAuto', false);
Titanium.API.info('Setze loginAuto = false');
} else if(Titanium.App.Properties.getBool('loginAuto') == false){
imageUrl = 'images/checkbox_checked.png';
Titanium.App.Properties.setBool('loginAuto', true);
Titanium.API.info('Setze loginAuto = true');
}
checkbox.image = imageUrl;
});
// Loginbutton bekommt Eventlistener, der bei Klick den Login durchführt.
loginBtn.addEventListener('click', function(e) {
// Datenbank wird erneut initialisiert, falls noch nicht vorhanden
var db_userdata = Titanium.Database.install("db/myHome4.sqlite", 'myHome4');
// Für den Fall das Benutzername und Passwort gespeichert werden sollen, werden sie hier in die DB geschrieben.
if(Titanium.App.Properties.getBool('loginAuto') == true){
Titanium.API.info('Speichere Name und Password in der Datenbank.');
db_userdata.execute("DELETE FROM login");
db_userdata.execute("INSERT INTO login (id, name, password) VALUES (1, ?, ?)", username.value, password.value);
Titanium.App.Properties.setString('loginName', username.value);
Titanium.App.Properties.setString('loginPassword', password.value);
} else {
db_userdata.execute("DELETE FROM login");
}
db_userdata.close();
var url = Titanium.App.Properties.getString('url') + '/services?wsdl';
var callparams = {
username: username.value,
password: password.value
};
/* Im Folgenden der suds Client (SOAP Client), der die SOAP Abfragen ausführt und Werte zurück liefert.
Login-Vorgang und Aufruf des Hauptmenüfensters
*/
Titanium.API.info(Titanium.App.Properties.getString('url'));
var suds = new SudsClient({
endpoint: url,
targetNamespace: Titanium.App.Properties.getString('url')
});
Titanium.API.info("TEST1111");
try {
Titanium.API.info("Test before function");
suds.invoke('login', callparams, function(xmlDoc) {
Titanium.API.info("Test after function is called");
var results = xmlDoc.documentElement.getElementsByTagName('return');
Titanium.API.info("another test comment");
Titanium.API.info(results);
if (results && results.length>0) {
var isAdmin = results.item(0).getElementsByTagName('admin');
if(isAdmin.item(0).text == "true") {
Titanium.API.info("isAdmin: true");
Titanium.App.Properties.setBool('isAdmin', true);
} else {
Titanium.API.info("isAdmin: false");
Titanium.App.Properties.setBool('isAdmin', false);
}
var userToken = results.item(0).getElementsByTagName('userToken');
Titanium.API.info("userToken: " + userToken.item(0).text);
Titanium.App.Properties.setString('userToken', userToken.item(0).text);
Titanium.App.Properties.setString('username', username.value);
//Rein oder raus???
//alert("Login erfolgreich! \n isAdmin: " + isAdmin.item(0).text + " \n userToken: " + userToken.item(0).text)
//Aufruf Hauptmenüfenster
openWindow('js/menue.js', 'Hauptmenü', true);
} else {
var resultsError = xmlDoc.documentElement.getElementsByTagName('S:Fault');
var errorString = resultsError.item(0).getElementsByTagName('faultstring');
Titanium.API.info("error: " + errorString.item(0).text);
alert(errorString.item(0).text);
}
});
} catch(e) {
alert(e);
Ti.API.error('Error: ' + e);
}
});
/* Eventlistener für den Logout-Button, bei Klick wird das Menüfenster geschlossen und die Variablen username, userToken und is
isadmin gelöscht
*/
Ti.App.addEventListener('eventLogout', function(event)
{
Titanium.App.Properties.removeProperty("username");
Titanium.App.Properties.removeProperty("userToken");
Titanium.App.Properties.removeProperty("isAdmin");
Titanium.API.info("Lösche Einstellungen...");
win2.close();
});
suds.js:
/*
* Definition der Parameter, die für SOAP Client notwendig sind
*
*/
var url = Titanium.App.Properties.getString('url') + '/services?wsdl';
/**
* Suds: A Lightweight JavaScript SOAP Client
* Copyright: 2009 Kevin Whinnery (http://www.kevinwhinnery.com)
* License: http://www.apache.org/licenses/LICENSE-2.0.html
* Source: http://github.com/kwhinnery/Suds
*/
function SudsClient(_options) {
function isBrowserEnvironment() {
try {
if (window && window.navigator) {
return true;
} else {
return false;
}
} catch(e) {
return false;
}
}
function isAppceleratorTitanium() {
try {
if (Titanium) {
return true;
} else {
return false;
}
} catch(e) {
return false;
}
}
//Funktion zur Erweiterung von Variablen (Objekten)
function extend(original, extended) {
for (var key in (extended || {})) {
if (original.hasOwnProperty(key)) {
original[key] = extended[key];
}
}
return original;
}
//Prüfung ob ein Objekt ein Array ist
function isArray(obj) {
return Object.prototype.toString.call(obj) == '[object Array]';
}
//Holt per get eine XMLHTTPRequest Object
function getXHR() {
return Titanium.Network.createHTTPClient();
}
//Aus einem String wird ein XML DOM object
function xmlDomFromString(_xml) {
xmlDoc = Titanium.XML.parseString(_xml);
return xmlDoc;
}
// Konvertiert ein Javascript OBbjekt in ein XML string
function convertToXml(_obj, namespacePrefix) {
var xml = '';
if (isArray(_obj)) {
for (var i = 0; i < _obj.length; i++) {
xml += convertToXml(_obj[i], namespacePrefix);
}
} else {
for (var key in _obj) {
if (namespacePrefix && namespacePrefix.length) {
xml += '<' + namespacePrefix + ':' + key + '>';
} else {
xml += '<'+key+'>';
}
if (isArray(_obj[key]) || (typeof _obj[key] == 'object' && _obj[key] != null)) {
xml += convertToXml(_obj[key]);
}
else {
xml += _obj[key];
}
if (namespacePrefix && namespacePrefix.length) {
xml += '</' + namespacePrefix + ':' + key + '>';
} else {
xml += '</'+key+'>';
}
}
}
return xml;
}
// Client Konfiguration
var config = extend({
endpoint:'https://localhost:8888/service',
targetNamespace: 'https://localhost:8888/service?wsdl',
envelopeBegin: '',
envelopeEnd: ''
},_options);
// Aufruf web service
this.invoke = function(_soapAction,_body,_callback) {
//Erstelle request body
var body = _body;
//Erlaubt einen String in einen XML body einzufügen - Ansonsten wird dieser aus einem XML Objekt erzeugt.
if (typeof body !== 'string') {
body = '<fron:'+_soapAction+'>';
body += convertToXml(_body);
body += '</fron:'+_soapAction+'>';
}
var ebegin = config.envelopeBegin;
config.envelopeBegin = ebegin.replace('PLACEHOLDER', config.targetNamespace);
//Erzeugt den Soapaction header
var soapAction = '';
if (config.targetNamespace.lastIndexOf('/') != config.targetNamespace.length - 1) {
soapAction = config.targetNamespace+'/'+_soapAction;
}
else {
soapAction = config.targetNamespace+_soapAction;
}
//Sende das XML document per HTTP_Post zum service endpoint
var xhr = getXHR();
xhr.onload = function() {
_callback.call(this, xmlDomFromString(this.responseText));
};
xhr.open('POST',config.endpoint);
xhr.setRequestHeader('Content-Type', 'text/xml;charset=UTF-8');
// xhr.setRequestHeader('SOAPAction', soapAction);
xhr.send(config.envelopeBegin+body+config.envelopeEnd);
Titanium.API.info(config.envelopeBegin+body+config.envelopeEnd);
Titanium.API.info("Test SUDS!");
};
}
I suppose that localhost will be the mobile (emulator) and not the hosting computer. Try binding the endpoints in Java to the machine name (not localhost) which is available in the network. Then point your SOAP connections to that machine.