14

I am doing project in android phonegap and I want to upload pic to the server.

But I am not getting idea, where should I put this code.

I can't show any buttons to upload photos, please help.

I am new in this. I refereed this code from phonegap documentation.

I am trying this for hours, but can't get the better solution.

It's my first android phonegap project.

Code:

   <head>
   <script type="text/javascript" charset="utf-8" src="cordova-2.4.0.js"></script>
   <script type="text/javascript" charset="utf-8">        
    document.addEventListener("deviceready", onDeviceReady, false);

    function onDeviceReady() {           
        navigator.camera.getPicture(uploadPhoto,
                function(message) { alert('get picture failed'); },
              { quality: 50, destinationType:    navigator.camera.DestinationType.FILE_URI,
                sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY }
             );
    }
    function uploadPhoto(imageURI) {
        var options = new FileUploadOptions();
        options.fileKey="file";
        options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
        options.mimeType="image/jpeg";

        var params = {};
        params.value1 = "test";
        params.value2 = "param";

        options.params = params;

        var ft = new FileTransfer();
        ft.upload(imageURI, encodeURI("http://some.server.com/upload.php"), win, fail, options);
    }

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

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

    </script>
 </head>
 <body>
    <h1>Example</h1>
    <p>Upload File</p>
 </body>
dmahapatro
  • 49,365
  • 7
  • 88
  • 117
Manu
  • 219
  • 1
  • 5
  • 14

5 Answers5

10

You solve your problem using the next code:

<script type="text/javascript">  
function uploadFromGallery() {

    // Retrieve image file location from specified source
    navigator.camera.getPicture(uploadPhoto,
                                function(message) { alert('get picture failed'); },
                                { quality: 50, 
                                destinationType: navigator.camera.DestinationType.FILE_URI,
                                sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY }
                                );

}

function uploadPhoto(imageURI) {
    var options = new FileUploadOptions();
    options.fileKey="file";
    options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1)+'.png';
    options.mimeType="text/plain";

    var params = new Object();

    options.params = params;

    var ft = new FileTransfer();
    ft.upload(imageURI, encodeURI("http://some.server.com/upload.php"), win, fail, options);
}

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

function fail(error) {
    alert("An error has occurred: Code = " + error.code);
    console.log("upload error source " + error.source);
    console.log("upload error target " + error.target);
}
</script>
</head>
<body>
   <a data-role="button" onClick="uploadFromGallery();">Upload from Gallery</a> 
</body>

See more info on this post: https://stackoverflow.com/a/13862151/1853864

Community
  • 1
  • 1
A. Magalhães
  • 1,511
  • 2
  • 22
  • 31
  • 2
    Thanks. Its correctly worked out. But we need to upload multiple images. Please give me a idea to upload multiple images using this cordova file transfer. – Sathiyaraj Jul 21 '14 at 12:45
  • Sorry bro :( I can't help you but I think you cannot upload multiple images using file transfer. When I found this solution, I used a plugin and some native code to Android and iOS. – A. Magalhães Jul 21 '14 at 21:14
  • i am also facing the similar issue but not able to fix it. can you please check this question stackoverflow.com/questions/40514847 – Roxx Nov 10 '16 at 10:55
  • Dear Sathiyaraj, for multiple image u can use this link its working 100% https://stackoverflow.com/questions/29405404/multiple-image-upload-to-server-in-cordova/38655736#38655736 – Eshan Chattaraj Sep 14 '17 at 06:11
5

Try the following code.

// A button will call this function
// To capture photo
function capturePhoto() {
    // Take picture using device camera and retrieve image as base64-encoded string
    navigator.camera.getPicture(uploadPhoto, onFail, { 
        quality: 50, destinationType: Camera.DestinationType.FILE_URI 
    });
}

// A button will call this function
// To select image from gallery
function getPhoto(source) {
    // Retrieve image file location from specified source
    navigator.camera.getPicture(uploadPhoto, onFail, { quality: 50,
        destinationType: navigator.camera.DestinationType.FILE_URI,
        sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
    });
}

function uploadPhoto(imageURI) {
    //If you wish to display image on your page in app
    // Get image handle
    var largeImage = document.getElementById('largeImage');

    // Unhide image elements
    largeImage.style.display = 'block';

    // Show the captured photo
    // The inline CSS rules are used to resize the image
    largeImage.src = imageURI;

    var options = new FileUploadOptions();
    options.fileKey = "file";
    var userid = '123456';
    var imagefilename = userid + Number(new Date()) + ".jpg";
    options.fileName = imagefilename;
    options.mimeType = "image/jpg";

    var params = new Object();
    params.imageURI = imageURI;
    params.userid = sessionStorage.loginuserid;
    options.params = params;
    options.chunkedMode = false;
    var ft = new FileTransfer();
    var url = "Your_Web_Service_URL";
    ft.upload(imageURI, url, win, fail, options, true);
}
//Success callback
function win(r) {
    alert("Image uploaded successfully!!");
}
//Failure callback
function fail(error) {
    alert("There was an error uploading image");
}
// Called if something bad happens.
// 
function onFail(message) {
    alert('Failed because: ' + message);
}

Create a button in your HTML page, on it's onclick event call following functions as per your requirement.

  • Call capturePhoto() function to capture and upload photo.
  • Call getPhoto() function to get image from gallery.

HTML should contain a buttons like:

<input name="button" type="button" onclick="capturePhoto()" value="Take Photo"/>

<input name="button" type="button" onclick="getPhoto();" value="Browse" />

Hope that helps.

Amol Chakane
  • 1,501
  • 2
  • 21
  • 43
  • how, where and when to call uploadPhoto(imageURI) function and what will be the value in imageURI parameter ??? – Code Spy Mar 22 '14 at 19:06
  • @jolly.exe `uploadPhoto()` get's called automatically in `capturePhoto()` success callback and the imageURI will be sent automatically. You do not have to call it explicitly anywhere. – Amol Chakane Mar 25 '14 at 11:13
  • i am also facing the similar issue but not able to fix it. can you please check this question stackoverflow.com/questions/40514847 – Roxx Nov 10 '16 at 10:55
0

This is one sample application which I did to upload a pic to server

function getphoto() 
{
   navigator.camera.getPicture(uploadPhoto, function(message)
   { 
     alert('get picture failed');
   },

   {
     quality: 10,destinationType:navigator.camera.DestinationType.FILE_URI,sourceType:navigator.camera.PictureSourceType.PHOTOLIBRARY }); 
   }

function uploadPhoto(imageURI) 
{   
    alert("imageURI: " + imageURI);
    document.getElementById("myimg").src = imageURI;
    alert("imageURI :  " + imageURI);
    var options = new FileUploadOptions(); 
    options.chunkedMode = false;
    options.fileKey = "recFile"; 
    var imagefilename = imageURI; 
    options.fileName = imagefilename; 
    options.mimeType = "image/jpeg"; 
    var ft = new FileTransfer(); 
    ft.upload(imageURI, "http://192.168.5.109:86/YourService.svc/SaveImage", win, fail, options); 
} 

function win(r) 
{ 
    alert("Sent = " + r.bytesSent); 
} 

function fail(error) 
{ 
    switch (error.code) 
    {  
     case FileTransferError.FILE_NOT_FOUND_ERR: 
      alert("Photo file not found"); 
      break; 
     case FileTransferError.INVALID_URL_ERR: 
      alert("Bad Photo URL"); 
      break; 
     case FileTransferError.CONNECTION_ERR: 
      alert("Connection error"); 
      break; 
    } 

    alert("An error has occurred: Code = " + error.code); 
}

Hope this helps

Thanks AB

Arun Bertil
  • 4,598
  • 4
  • 33
  • 59
0

Well, It's work for me.

trustAllHosts: Optional parameter, defaults to false. If set to true, it accepts all security certificates. This is useful since Android rejects self-signed security certificates. Not recommended for production use. Supported on Android and iOS. (boolean)

The last parameter add true how boolean.

Before

var ft = new FileTransfer();
ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options);

After

var ft = new FileTransfer();
ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options, true);
John
  • 544
  • 4
  • 19
0

enter link description here

This is a link for 100% working method for uploading multiple image to server via cordova or phonegap function using html java script

Multiple Image upload to server in Cordova

Eshan Chattaraj
  • 368
  • 1
  • 6
  • 19