SAP Mobile App Development

How to Upload Images to server in SAPUI5 Hybrid App?

                      This is a step by step tutorial showing how to upload or transfer images to server from  SAPUI5 Hybrid Mobile App.Iam uploading the image taken in the previous tutorial to a php server with the use of cordova File Transfer plugin.File Transfer plugin allows us to upload and download files.
                       This tutorial is continuation of How to implement Camera functionality in SAPUI5 hybrid mobile App?

Pre-requisites

  1. Windows system setup with SAP Mobile Platform SDK installed and Hybrid App Toolkit configured.(If not setup already visit my  blog post Windows System Setup for Developing Mobile Apps with SAPWebIDE and SAP Mobile SDK )
  2. Created basic SAPUI5 Hybrid Mobile App(If you haven't created one yet follow previous blog How to Create SAPUI5 Hybrid Mobile App with SAP Web IDE).
  3. Device Camera functionality implemented already.(Visit blog post How to implement Camera functionality in SAPUI5 hybrid mobile App?)


Steps

  1. Start HAT Connector ,Open SAP Web IDE and check HAT connectity is avialable.If not familiar follow pre-requisites 2 section.
  2. Right click on project folder and choose Project Settings.Go to Hybrid App Toolkit->Hybrid App Configuration.Under Plugins section tick mark cordova Camera , Access File and File Transfer plugins and press save button.
  3. Open View1.view.xml file.Add a new sap.m.Button control.On clicking this button the image will be uploaded to php server.Add press event to the button.My modified view code below.

  4. <core:View
     xmlns:core="sap.ui.core"
     xmlns:mvc="sap.ui.core.mvc"
     xmlns="sap.m" controllerName="myFirstMobileApp.view.View1"
     xmlns:html="http://www.w3.org/1999/xhtml">
     <Page title="CameraApp">
      <content>
       <HBox justifyContent="SpaceAround">
        <items>
         <Button text="Capture Photo" press="onCapture"></Button>
         <Button text="Select Photo" press="onSelect"></Button>
        </items>
       </HBox>
       <HBox width="100%" justifyContent="Center">
        <items>
         <Image width="300px" height="300px" id="myImage"></Image>
        </items>
       </HBox>
       <HBox width="100%" justifyContent="Center">
        <items>
         <Button text="Upload Photo" press="onUpload"></Button>
        </items>
       </HBox>
      </content>
     </Page>
    </core:View>
    

  5. Open View1.controller.js.Inside onUpload method will code upload logic.We will make use of upload method of File Transfer api.My controller code is below.Replace php url with your url.

  6. sap.ui.controller("myFirstMobileApp.view.View1", {
    
        oView: null,
        onInit: function() {
            oView = this.getView();
        },
        onCapture: function() {
            navigator.camera.getPicture(this.onSuccess, this.onFail, {
                quality: 75,
                targetWidth: 300,
                targetHeight: 300,
                sourceType: navigator.camera.PictureSourceType.CAMERA,
                destinationType: navigator.camera.DestinationType.FILE_URI
            });
        },
        onSelect: function() {
            navigator.camera.getPicture(this.onSuccess, this.onFail, {
                quality: 75,
                targetWidth: 300,
                targetHeight: 300,
                sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY,
                destinationType: navigator.camera.DestinationType.FILE_URI
            });
        },
        onSuccess: function(imageData) {
            var imageId = oView.byId("myImage");
            imageId.setSrc(imageData);
    
        },
        onFail: function(message) {
            alert("Failed because: " + message);
        },
        onUpload:function(){
     imageUri = oView.byId("myImage").getSrc();
     alert(imageUri);
            var url=encodeURI("");//you can add your php url here
            var params = new Object();
            params.your_param_name = "something";  //you can send additional info with the file
    
            var options = new FileUploadOptions();
            options.fileKey = "file"; //depends on the api
            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 = true; //this is important to send both data and files
    
            var ft = new FileTransfer();
            ft.upload(imageUri, url, this.onSuccesFileTransfer, this.onErrorFileTransfer, options); 
        },
       
        onSuccesFileTransfer:function(success){
            alert("success"+JSON.stringify(success));
        },
        onErrorFileTransfer:function(error){
            alert("error"+JSON.stringify(error));
        }
    
    });
    

  7. To test the App Right Click ->Run->Run on Local Device/Simulator->Android Device.
  8. See app screenshot below.
NOTE:sample code inside php server is below.It is a rest supporting php url with post method.Dont forget to create a upload folder

    <?php
    //Allow Headers
    header('Access-Control-Allow-Origin: *');
    //print_r(json_encode($_FILES));
    $new_image_name = urldecode($_FILES["file"]["name"]).".jpg";
    //Move your files into upload folder
    move_uploaded_file($_FILES["file"]["tmp_name"], "upload/".$new_image_name);
    ?>
    


If you enjoyed this post, Please Share!!

11 comments :

  1. Very nice blog, where do we actually create the upload folder ? Inside xampp htdocs folder?

    ReplyDelete
    Replies
    1. Thank you Mafika.Iam not an expert in PHP.When I asked Our PHP Expert he recommended creating the folder inside the project folder.Of course it will be inside xampp htdocs folder.

      Delete
  2. Can we use sap.ui.unified.FileUploader instead of Cordova FIleTransfer? It seems cordova FT os discontinued

    ReplyDelete
    Replies
    1. I first tried with fileuploader but I was not able to get the file reference from fileuploader control.You can try and let us know..
      Thanks

      Delete

  3. Hey! Do you use Twitter? I'd like to follow you if that would be okay. I'm absolutely enjoying your blog and look forward to new posts. gmail login

    ReplyDelete
    Replies
    1. Yes Iam using twitter.search for techippo. thanks for commenting.

      Delete
  4. Hello,
    I am using this code for select an image from gallery
    onSelect: function() {
    navigator.camera.getPicture(this.onSuccess, this.onFail, {
    quality: 75,
    targetWidth: 300,
    targetHeight: 300,
    sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY,
    destinationType: navigator.camera.DestinationType.FILE_URI
    });
    },
    onSuccess: function(imageData) {
    var imageId = oView.byId("myImage");
    imageId.setSrc(imageData);

    },
    in hybrid android app. but here inside image data i am getting image path i.e,"File://androiddevice/localstorage/image.jpg" instead of base64. Now my requirement is i want to image content in base64.

    ReplyDelete
    Replies
    1. If you want base64 data use
      'destinationType: navigator.camera.DestinationType.DATA_URL' instead of destinationType: navigator.camera.DestinationType.FILE_URI.. Using File_URI is reccommended.

      Delete
    2. Hi Rajeesh,
      Thank you for the wonderful tutorial.
      Looks like the picture taken by camera is not with good quality though i have set quality to 100. Any idea on this? Please.

      Delete
    3. Which device you are using? on newer devices picture quality will be good. Using FILE_URI as the 'Camera.destinationType' is recommended.

      Delete
  5. can u provide code

    ReplyDelete

Powered by Blogger.