11

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> 

4 Answers 4

12

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> 
Sign up to request clarification or add additional context in comments.

6 Comments

Hi ! I am using your code and does work fine with taking image and uploading to server! But it does not work with displaying the image, though it does assigns the path to image.src but cannot display the image :(
Can it be that I am missing some plugin? I have posted the complete question over there: stackoverflow.com/questions/28125080/…
I looked at your post on the link. Your modified code is trying to show the image in the uploadPhoto function which is never called untill you upload the photo. Put it in a function like onPhotoURISuccess in the example. Look at the getPhoto function in the example. It's the first parameter in navigator.camera.getPicture(YourFunctionNameHereThatDisplayTheImage, ...)
My uploadPhoto function is the same as your onPhotoURISuccess and I if you look at it, it is the very first function :)
I don't know why but I am not able to select image with above code, but if i remove form tag from body, Image gets retrieved. Please help?
|
1

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.

7 Comments

what if form fields are empty..params is just static values. i want to send image on form submit which is not happening.
Fill params with your form contents before sending... is you use jQuery something like params.name = $('#inputName').val() and so on..
thanks for the suggestion, but select avatar button is the first element in the form.what u r saying is to fill up the fields and then upload image with input fields parameter. I want to upload image on submit button of the form. Any suggestion?
@user3420072 you can try to manually process what and how to submit by using "onSubmit" in the form. Also you can try doubtful trick: add to form invisible input with it's value equals to image base64 string
@Regent worth noting that on some devices (notably ipad mini and cheap androids) you can incur in memory errors using base64 images from camera.
|
1

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 } } 

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.