Navneeth
Navneeth

Reputation: 988

PhoneGap upload Image to server on form submit

I am facing problem here as in phonegap image is uploaded to the server once u select a picture.I don't want to upload image before submitting form. Image is uploaded automatically to server which is something i don't want.I want to upload image with the form, where form contains many more fields which is required to send along with image. What are the possible ways to submit with form?

<!DOCTYPE HTML >
<html>
<head>
<title>Registration Form</title>
<script type="text/javascript" charset="utf-8" src="phonegap-1.2.0.js"></script>
<script type="text/javascript" charset="utf-8">

    // Wait for PhoneGap to load
    document.addEventListener("deviceready", onDeviceReady, false);

    // PhoneGap is ready
    function onDeviceReady() {
// Do cool things here...
    }

    function getImage() {
        // 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);
        options.mimeType="image/jpeg";

        var params = new Object();
        params.value1 = "test";
        params.value2 = "param";

        options.params = params;
        options.chunkedMode = false;

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

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

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

    </script>
</head>
<body>
<form id="regform">
<button onclick="getImage();">select Avatar<button>
<input type="text" id="firstname" name="firstname" />
<input type="text" id="lastname" name="lastname" />
<input type="text" id="workPlace" name="workPlace" class="" />
<input type="submit" id="btnSubmit" value="Submit" />
</form>
</body>
</html>

Upvotes: 11

Views: 30966

Answers (4)

bozdoz
bozdoz

Reputation: 12890

I could not get these plugins to upload a file with the other answers.

The problem seemed to stem from the FileTransfer plugin, which states:

fileURL: Filesystem URL representing the file on the device or a data URI.

But that did not appear to work properly for me. Instead I needed to use the File plugin to create a temporary file using the data uri to get me a blob object: in their example, writeFile is a function which takes a fileEntry (returned by createFile) and dataObj (blob). Once the file is written, its path can be retrieved and passed to the FileTransfer instance. Seems like an awful lot of work, but at least it's now uploading.

Upvotes: 0

Ved
Ved

Reputation: 2701

I also faced same problem, but I have done using two server side calls on one click. In this, in first call submit data and get its id in callback using JSON then upload image using this id. On server side updated data and image using this id.

$('#btn_Submit').on('click',function(event) {
   event.preventDefault();
   if(event.handled !== true)
   {
      var ajax_call = serviceURL; 
      var str = $('#frm_id').serialize();                 
      $.ajax({
      type: "POST",
      url: ajax_call,
      data: str,
      dataType: "json",
      success: function(response){
              //console.log(JSON.stringify(response))
        $.each(response, function(key, value) { 
              if(value.Id){                               
                   if($('#vImage').attr('src')){
                         var imagefile = imageURI; 
                          $('#vImage').attr('src', imagefile);
                        /* Image Upload Start */
                          var ft = new FileTransfer();                     
                        var options = new FileUploadOptions();                      
                        options.fileKey="vImage";                      
                        options.fileName=imagefile.substr(imagefile.lastIndexOf('/')+1);
                        options.mimeType="image/jpeg";  
                        var params = new Object();
                        params.value1 = "test";
                        params.value2 = "param";                       
                        options.params = params;
                        options.chunkedMode = false;                       
                        ft.upload(imagefile, your_service_url+'&Id='+Id+'&mode=upload', win, fail, options); 
                      /* Image Upload End */
                   }      
               }

             }); 
          }
     }).done(function() {
          $.mobile.hidePageLoadingMsg();              
     })

   event.handled = true;
  }
  return false;
});

On server side using PHP

if($_GET['type'] != "upload"){
  // Add insert logic code
}else if($_GET['type'] == "upload"){
  // Add  logic for image 
  if(!empty($_FILES['vImage']) ){ 
    // Copy image code and update data  
  }
}

Upvotes: 1

edg
edg

Reputation: 669

Create two functions you can call separately. One function for just getting the image, and another function to upload the image.

You can do something like below.

<!DOCTYPE html>
<html>
  <head>
    <title>Submit form</title>

    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8">

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

    // Wait for device API libraries to load
    //
    document.addEventListener("deviceready",onDeviceReady,false);

    // device APIs are available
    //
    function onDeviceReady() {
        pictureSource = navigator.camera.PictureSourceType;
        destinationType = navigator.camera.DestinationType;
    }


    // Called when a photo is successfully retrieved
    //
    function onPhotoURISuccess(imageURI) {

        // Show the selected image
        var smallImage = document.getElementById('smallImage');
        smallImage.style.display = 'block';
        smallImage.src = imageURI;
    }


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

    function uploadPhoto() {

        //selected photo URI is in the src attribute (we set this on getPhoto)
        var imageURI = document.getElementById('smallImage').getAttribute("src");
        if (!imageURI) {
            alert('Please select an image first.');
            return;
        }

        //set upload options
        var options = new FileUploadOptions();
        options.fileKey = "file";
        options.fileName = imageURI.substr(imageURI.lastIndexOf('/')+1);
        options.mimeType = "image/jpeg";

        options.params = {
            firstname: document.getElementById("firstname").value,
            lastname: document.getElementById("lastname").value,
            workplace: document.getElementById("workplace").value
        }

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

    // Called if something bad happens.
    //
    function onFail(message) {
      console.log('Failed because: ' + message);
    }

    function win(r) {
        console.log("Code = " + r.responseCode);
        console.log("Response = " + r.response);
        //alert("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>
    <form id="regform">
        <button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">Select Photo:</button><br>
        <img style="display:none;width:60px;height:60px;" id="smallImage" src="" />

        First Name: <input type="text" id="firstname" name="firstname"><br>
        Last Name: <input type="text" id="lastname" name="lastname"><br>
        Work Place: <input type="text" id="workplace" name="workPlace"><br>
        <input type="button" id="btnSubmit" value="Submit" onclick="uploadPhoto();">
    </form>
  </body>
</html>

Upvotes: 12

Paolo Casciello
Paolo Casciello

Reputation: 8202

You're already sending custom fields in your example.

var params = new Object();
params.value1 = "test";
params.value2 = "param";

options.params = params;

Just populate params with your form fields.

Upvotes: 1

Related Questions