PhoneGap upload Image to server on form submit

前端 未结 4 1617
南旧
南旧 2021-01-31 06:29

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 automatic

相关标签:
4条回答
  • 2021-01-31 06:45

    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  
      }
    }
    
    0 讨论(0)
  • 2021-01-31 06:53

    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.

    0 讨论(0)
  • 2021-01-31 06:58

    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.

    0 讨论(0)
  • 2021-01-31 07:08

    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>
    
    0 讨论(0)
提交回复
热议问题