upload image to server (php)

4,736 views
Skip to first unread message

eyal

unread,
Aug 2, 2012, 4:40:02 PM8/2/12
to phon...@googlegroups.com
i try to upload an image to the server 
my script is

function success(response) {
        alert("4");
      };
      // callback if the photo fails to upload successfully.

      function fail(error) {
        alert("3" + error.code);
      };

    function uploadPhoto()
    {
        var imageFile = document.getElementById("test_img").src;
        alert("1" + imageFile);




        var ft,options;


        options = new FileUploadOptions();
        options.fileKey = "profile_image";
          // name of the file:
          options.fileName = imageFile.substr(imageFile.lastIndexOf('/') + 1);
          // mime type:
          options.mimeType = "multipart/form-data";
          params = {
            val1: "some value",
            val2: "some other value"
          };
          options.params = params;



        ft = new FileTransfer();
        ft.upload(imageFile, 'http://192.168.123.199/saveImage.php', success, fail, options,false);
        alert("2 " + imageFile);

    };

i see alert 1,2 and then nothing
my php code 

<?php// Directory where uploaded images are saved

$target_path = "tmp/";

$target_path = $target_path . basename( $_FILES['profile_image']['name']); 

if(move_uploaded_file($_FILES['profile_image']['name'], $target_path)) {
echo "The file ".  basename( $_FILES['profile_image']['name']). 
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
my logcat 
08-02 23:21:05.835: D/FileTransfer(16094): upload content://media/external/images/media/1889 to http://192.168.123.199/saveImage.php
08-02 23:21:05.835: D/FileTransfer(16094): fileKey: profile_image
08-02 23:21:05.835: D/FileTransfer(16094): fileName: 1889
08-02 23:21:05.835: D/FileTransfer(16094): mimeType: multipart/form-data
08-02 23:21:05.835: D/FileTransfer(16094): params: {"val1":"some value","val2":"some other value"}
08-02 23:21:05.835: D/FileTransfer(16094): trustEveryone: false
08-02 23:21:05.835: D/FileTransfer(16094): chunkedMode: true
08-02 23:21:08.740: D/dalvikvm(16094): GC_CONCURRENT freed 252K, 48% free 3122K/5959K, external 882K/1314K, paused 8ms+14ms

jcesarmobile

unread,
Aug 2, 2012, 6:22:55 PM8/2/12
to phon...@googlegroups.com
Try sending the base 64 image data, and decoding it on the server.

Berman Eyal

unread,
Aug 2, 2012, 10:35:41 PM8/2/12
to phon...@googlegroups.com

Where i change it to base 64?

--
-- You received this message because you are subscribed to the Google
Groups "phonegap" group.
To post to this group, send email to phon...@googlegroups.com
To unsubscribe from this group, send email to
phonegap+u...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/phonegap?hl=en?hl=en
 
For more info on PhoneGap or to download the code go to www.phonegap.com
 
To compile in the cloud, check out build.phonegap.com
 
 

eyal

unread,
Aug 3, 2012, 12:04:20 AM8/3/12
to phon...@googlegroups.com
i change it to base64 but it still dosent get to the server my new code 

var pictureSource;   // picture source
    var destinationType; // sets the format of returned value 

    document.addEventListener("deviceready",onDeviceReady,false);

    function onDeviceReady() {
        pictureSource=navigator.camera.PictureSourceType;
        destinationType=navigator.camera.DestinationType;
    }

       function onPhotoDataSuccess(imageData) {
      
       console.log(imageData);

       var smallImage = document.getElementById('smallImage');

       smallImage.style.display = 'block';

           smallImage.src = "data:image/jpeg;base64," + imageData;
           
           $.ajax({
                type: "POST",
                url: 'http://192.168.123.199/saveImage.php',
                data: { image_data: imageData },
                beforeSend: function() {
                $("#comment").text("Start ajax ");
                },
                success: function (data) {
                    $("#comment").text("Uploaded!");
                },
                error: function (request,error){
                console.log(arguments);
                $("#comment").text("Error!");
                }
            });
           
           
           
    }

    // A button will call this function
    //
    function capturePhoto() {
      // Take picture using device camera and retrieve image as base64-encoded string
      navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
        destinationType: destinationType.DATA_URL });
    }

    // A button will call this function
    //
    function capturePhotoEdit(source) {
      // Take picture using device camera, allow edit, and retrieve image as base64-encoded string  
      navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50, 
        destinationType: destinationType.DATA_URL,sourceType: source });
    }

     function onFail(message) {
      alert('Failed because: ' + message);
    }

i still cant get response from server, maybe it's a cross domain problem?
i gave in config.xml
<access origin="http://192.168.123.199*"/>

jcesarmobile

unread,
Aug 3, 2012, 3:56:09 AM8/3/12
to phon...@googlegroups.com
and the console.log(imageData); shows something?

I think <access origin="http://192.168.123.199*"/> shouldn't include the http:// part, try with just <access origin="*"/> to make sure this isn't the problem

eyal

unread,
Aug 3, 2012, 5:02:23 AM8/3/12
to phon...@googlegroups.com
when i use small data like

var imageData  = "R0lGODlhBgASALMAAOfn5+rq6uvr6+zs7O7u7vHx8fPz8/b29vj4+P39/f///wAAAAAAAAAAAAAAAAAAACwAAAAABgASAAAIMAAVCBxIsKDBgwgTDkzAsKGAhxARSJx4oKJFAxgzFtjIkYDHjwNCigxAsiSAkygDAgA7";

it's work so i think that the problem is with post data size. i change my wamp setting

post_max_size = 750M 
upload_max_filesize = 750M 
max_execution_time = 5000 
max_input_time = 5000 
memory_limit = 1000M

but still dont work for large data. 

eyal

unread,
Aug 3, 2012, 7:00:10 AM8/3/12
to phon...@googlegroups.com
the problem is with file size - with base64 and posting with ajax or filetransfer the limit is 1.4k
i dont know if the problem is in my server or in my app...

eyal

unread,
Aug 6, 2012, 8:05:28 AM8/6/12
to phon...@googlegroups.com
Fixed it' the problem was in the server side, i change it to asp.net on real server and it's work fine


On Thursday, August 2, 2012 11:40:02 PM UTC+3, eyal wrote:

Suresh_s_Kumar

unread,
Aug 7, 2012, 4:11:43 AM8/7/12
to phon...@googlegroups.com
Hi Eyal,
 
I am facing same kind of issue what you have faced, Please can you share the working code (Both js & asp.net).
 
Thanks in Advance,
Suresh

Berman Eyal

unread,
Aug 7, 2012, 4:14:53 AM8/7/12
to phon...@googlegroups.com
i will post an basic example in some hours when i get home.

--
-- You received this message because you are subscribed to the Google
Groups "phonegap" group.
To post to this group, send email to phon...@googlegroups.com
To unsubscribe from this group, send email to
phonegap+u...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/phonegap?hl=en?hl=en
 
For more info on PhoneGap or to download the code go to www.phonegap.com
 
To compile in the cloud, check out build.phonegap.com
 
 



--

Suresh_s_Kumar

unread,
Aug 7, 2012, 5:57:21 AM8/7/12
to phon...@googlegroups.com
Thanks Eyal, Waiting for your response!

For more options, visit this group at
http://groups.google.com/group/phonegap?hl=en?hl=en
 
For more info on PhoneGap or to download the code go to www.phonegap.com
 
To compile in the cloud, check out build.phonegap.com
 
 

Suresh_s_Kumar

unread,
Aug 7, 2012, 7:39:35 AM8/7/12
to phon...@googlegroups.com
hi
 
i have tried the below sample. But gets the Error Code as "3". While debug got the expansion of error as connection error.
 
Please help us.
 
Details of JS Files:
 

function win(r) {
alert("Code = " + r.responseCode);
alert("Response = " + r.response);
alert("Sent = " + r.bytesSent);
}

function fail(error) {
alert("An error has occurred: Code = " + error.code);
alert("upload error source " + error.source);
alert("upload error target " + error.target);
}

function onPhotoDataSuccess(imageURI)
{
alert("OnPhotoDataSuccess Method Called");
alert(imageURI);
try
{
app.setValue('imageHolder', imageURI);


//File Upload - Begins

var options = new FileUploadOptions();
options.chunkedMode = false;
options.fileKey="recFile";
var imagefilename = imageURI.substr(imageURI.lastIndexOf('/')+1);
options.fileName=imagefilename;
options.mimeType="image/jpeg";

var ft = new FileTransfer();
alert("imagefilename"+imagefilename);
ft.upload(imageURI, encodeURI("http://localhost:46591/Service1.asmx/SaveImage"), win, fail, options);

//File Uoload - Ends
}
catch(e)
{
alert("Error on onPhotoDataSuccess : " + e);
}
}

function onFail(message)
{
alert("Error:=" + message);
}

function handler_actionBtn_onClick(mouseev){


// Take picture using device camera and retrieve image

navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50, targetWidth: 300, targetHeight:200,destinationType : Camera.DestinationType.FILE_URI });
}  

Details of ASMX Files:
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace WebService1
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string SaveImage()
        {
            HttpPostedFile file = HttpContext.Current.Request.Files["recFile"];
            if (file == null)
                return null;
            string targetFilePath = "c:\\deposit\\" + file.FileName;
            file.SaveAs(targetFilePath);
            return file.FileName.ToString();
        }
    }
}
 
Thanks in Advance.
Suresh
 


For more options, visit this group at
http://groups.google.com/group/phonegap?hl=en?hl=en
 
For more info on PhoneGap or to download the code go to www.phonegap.com
 
To compile in the cloud, check out build.phonegap.com
 
 

eyal

unread,
Aug 7, 2012, 7:46:47 AM8/7/12
to phon...@googlegroups.com
do you run it on the emulator or on a device in wireless?
do you have localhost in white-list?



i couldn't get the android get to my localhost on wireless (i think my router close it)

eyal

unread,
Aug 7, 2012, 7:49:10 AM8/7/12
to phon...@googlegroups.com
the problem was just with visual studio server if i use the wamp server everything was ok.


On Tuesday, August 7, 2012 2:39:35 PM UTC+3, Suresh_s_Kumar wrote:

Suresh Kumar

unread,
Aug 7, 2012, 7:56:47 AM8/7/12
to phon...@googlegroups.com
Thanks. I have connected the device directly to my system & using VS 2010 along with IIS Server.

jcesarmobile

unread,
Aug 7, 2012, 9:04:35 AM8/7/12
to phon...@googlegroups.com
You can't use localhost if you test on a real device, you have to use the server local ip
for a real device, localhost is the device, and your server isn't in your device, when you run the emulator it works, because localhost is the same computer with the server and the emulator

eyal

unread,
Aug 7, 2012, 1:18:05 PM8/7/12
to phon...@googlegroups.com
A simple example 

the js
<!DOCTYPE HTML>
<html>
<head>
<title>Cordova</title>
<link rel="stylesheet" href="style.css" media="screen" />
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript" charset="utf-8" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value 

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}

</script>




</head>
<body>
<script type="text/javascript" charset="utf-8">
var myData = "";
$(document).ready(function() {
$("#getDataFromServer").click(function() {
var imageData = myData;
$.ajax({
type : "POST",
data : {
image : imageData
},
beforeSend : function() {
$("#comment2").text("Start ajax " + imageData.length);
},
success : function(data) {
$("#comment2").text("Uploaded! " + data);
},
error : function(request, error) {
$("#comment2").text("Error! " + error);
}
});
});
})

function capturePhotoEdit(source) {
navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
quality : 50,
destinationType : destinationType.DATA_URL,
sourceType : source
});
}

function onFail(message) {
alert('Failed because: ' + message);
}

function onPhotoDataSuccess(imageData) {

console.log(imageData);

var smallImage = document.getElementById('smallImage');

smallImage.style.display = 'block';

smallImage.src = "data:image/jpeg;base64," + imageData;
myData = imageData;
$("#comment").text(imageData.length);

}
</script>
<h1>Hello World</h1>
<p>
<a href="#" onclick="capturePhotoEdit(pictureSource.PHOTOLIBRARY);">get
image</a>
</p>
<p>
<a href="#" id="getDataFromServer">send image</a>
</p>
<span id="comment2"></span>
<img style="display: none; width: 100px; height: 100px;"
id="smallImage" src="" />
<span id="imagename"></span>
<span id="comment"></span>

</body>
</html>

the asp.net handler saveImage.ashx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;

namespace Recepies
{
    /// <summary>
    /// Summary description for saveImage
    /// </summary>
    public class saveImage : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                string filePath = "";
                filePath = context.Server.MapPath(".");
                string fileName = RandomString(10);
                string myImage = context.Request.Form["image"];
                if (myImage.Length > 0)
                {
                    File.WriteAllBytes(filePath + "/upload/" + fileName + ".jpg", Convert.FromBase64String(myImage));
                    context.Response.ContentType = "text/plain";
                    context.Response.Write("File was saved - " + fileName + ".jpg");
                }
                else
                {
                    context.Response.ContentType = "text/plain";
                    context.Response.Write("File was not saved");
                }
            }
            catch (Exception ex)
            {

                context.Response.ContentType = "text/plain";
                context.Response.Write(ex.Message);
            }
            
        }

        private static Random random = new Random((int)DateTime.Now.Ticks);//thanks to McAden
        private string RandomString(int size)
        {
            StringBuilder builder = new StringBuilder();
            char ch;
            for (int i = 0; i < size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }

            return builder.ToString();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

On Thursday, August 2, 2012 11:40:02 PM UTC+3, eyal wrote:

Suresh_s_Kumar

unread,
Aug 8, 2012, 3:31:53 AM8/8/12
to phon...@googlegroups.com
Hi Eyal,
 
Thanks again for time & support regarding this error!
 
I have tried as you have mentioned, we have server instead of localhost, we hosted our service in the server & tried the sample. Still getting "Connection Error". We unable to find out the issue.
 
We have some questions towards it.
1) the server is in our intranet.
So the question  is whether intranet system ip will support or we need to expose the IP (domain) & we need to try it out.
 
This is our question.
 
Please need your help on understanding.
 
Thanks Again
Suresh

Eyal Berman

unread,
Aug 8, 2012, 3:52:58 AM8/8/12
to phon...@googlegroups.com
if you can browse to the service from the device browser it's ok

did you get to it?

if no, maybe your server close to wifi access.

Eyal

Suresh_s_Kumar

unread,
Aug 13, 2012, 3:09:59 AM8/13/12
to phon...@googlegroups.com
Eyal,
 
Thanks for the informatiom. We took some time set up the server.
 
Now when we try below server, we are getting "Internal Server Error".
 
Please some one help on this.
 
The url we tried is http://vadivel.co.in/ws/Service1.asmx/GetName
 
We just tried to connect the server, then we thought of writing your code to transfer the image.
 
But unfortunately the connection itself creates problem.
 
Thanks in Advance
Suresh

Eyal Berman

unread,
Aug 13, 2012, 5:41:46 AM8/13/12
to phon...@googlegroups.com
you need to try to see what is your error on the page.

To enable the details of this specific error message to be viewable on remote machines, please create a <customErrors> tag within a "web.config" configuration file located in the root directory of the current web application. This <customErrors> tag should then have its "mode" attribute set to "Off". 

Eyal 

Suresh Kumar

unread,
Aug 13, 2012, 5:56:16 AM8/13/12
to phon...@googlegroups.com
EYAL,
 
Thanks i will check that.
 
Please can suggest any 3rd party API to upload image & test the functionality, as we finding difficulty to test in out test domain.
 
Thanks again for your help.
 
Suresh


 

--
-- You received this message because you are subscribed to the Google
Groups "phonegap" group.
To post to this group, send email to phon...@googlegroups.com
To unsubscribe from this group, send email to

Eyal Berman

unread,
Aug 13, 2012, 6:53:45 AM8/13/12
to phon...@googlegroups.com
do you have a server that can run asp.net?

Suresh Kumar

unread,
Aug 13, 2012, 7:00:25 AM8/13/12
to phon...@googlegroups.com
Eyal,
 
we are having. Please check the delow link aslo.
 
 
in that we are trying to call GetName service, it will just return some string, thats all. Even this service, we could not call from mobile device, but i can call from any other web projects.
 
Please advice.
 
Suresh

Eyal Berman

unread,
Aug 13, 2012, 7:20:48 AM8/13/12
to phon...@googlegroups.com
install this project on your server, it's using asp.net 4

it will upload a base64 image to the folder uploads (give permissions to the folder)

it's the same code that is in my answer above
images.zip

Suresh Kumar

unread,
Aug 13, 2012, 2:06:05 PM8/13/12
to phon...@googlegroups.com
EYAL,
 
I have uploaded your code & called from my phonegap application as shown below. But still i am getting error which is also attached. please help us where we are doing mistake.
 
Code Details:
 
<!DOCTYPE HTML>
<html>
<head>
<title>Cordova</title>
<link rel="stylesheet" type="text/css" href="css/index.css" />

<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript" charset="utf-8">
    var pictureSource; // picture source
    var destinationType; // sets the format of returned value
    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
        pictureSource = navigator.camera.PictureSourceType;
        destinationType = navigator.camera.DestinationType;
    }
</script>
</head>
<body>
 <script type="text/javascript" charset="utf-8">
     var myData = "";
     $(document).ready(function () {
         $("#getDataFromServer").click(function () {
             var imageData = myData;
             alert("getdatafromServer Method");
             $.ajax({
                 type: "POST",
                 url: 'http://vadivel.co.in/ws1/saveImage.ashx',

                 data: {
                     image: imageData
                 },
                 beforeSend: function () {
                     $("#comment2").text("Start ajax " + imageData.length);
                 },
                 success: function (data) {
                     $("#comment2").text("Uploaded! " + data);
                 },
                 error: function (request, error) {

                     $("#comment2").text("Error! " + error);
                 }
             });
         });
     })
    
        function capturePhotoEdit(source) {
         navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
             quality: 50,
             destinationType: destinationType.DATA_URL,
             sourceType: source
         });
     }
    
        function onFail(message) {
         alert('Failed because: ' + message);
     }
     function onPhotoDataSuccess(imageData) {
         console.log(imageData);
         var smallImage = document.getElementById('smallImage');
         smallImage.style.display = 'block';
         smallImage.src = "data:image/jpeg;base64," + imageData;
         myData = imageData;
         alert(imageData.length);

         $("#comment").text(imageData.length);
     }
 </script>
 <h1>Hello World</h1>
 <p>
  <a href="#" onclick="capturePhotoEdit(pictureSource.PHOTOLIBRARY);">get image</a>
 </p>
 <p>
  <a href="#" id="getDataFromServer">send image</a>
 </p>
 <span id="comment2"></span>
 <img style="display: none; width: 100px; height: 100px;" id="smallImage" src="" />
 <span id="imagename"></span>
 <span id="comment"></span>
</body>
</html>
 
Error Details:
 

Attached as image.

  Thanks,
Suresh
 
PhoneGap-Error.png

Eyal Berman

unread,
Aug 13, 2012, 2:25:28 PM8/13/12
to phon...@googlegroups.com
your code work fine, look at my picture in your server.

maybe your router stop your connaction to the server?

Suresh Kumar

unread,
Aug 13, 2012, 2:55:14 PM8/13/12
to phon...@googlegroups.com
Thanks EYAL, for your timely response. i will check & upate you in the morning, as i could not see any images now. i will check in the server itself tomorrow & o reply.
 
Regarding the issue, i will check with network team also. If you have any ideas on that, please let us know.
 
Thanks in Advance,
Suresh

Suresh_s_Kumar

unread,
Aug 14, 2012, 10:25:02 AM8/14/12
to phon...@googlegroups.com
EYAL,
 
Thanks a lot. Atlast we got the output in Android device, when we capture the image & successfully we are able to upload the image.
 
Still we are facing the issues in BB, but we can do it from our side.
 
Thanks a lot again.
 
Suresh & Team

Suresh Kumar

unread,
Aug 17, 2012, 12:59:15 AM8/17/12
to phon...@googlegroups.com
EYAL,
 
Greetings!
 
I have one issue in the solution (WS) mostly.
 
Issue:
 
1) When i send photo from my Android Device to external server, i am getting the same image twice with different file name.
 
Where is the problem? Can you suggest.
 
Thanks in Advance.
Suresh
Reply all
Reply to author
Forward
0 new messages