Upload file to server using ionic

I am building a mobile app using ionic. One of the usecase is to let the user browse a file and upload it to the backend server (which exposes a rest service).

On the UI, I am using the html file tag

<input type="file" ng-select="uploadFile($files)" multiple>

This opens a file browser to select a file. Then in the controller, I am doing the following

.controller(‘UploadDocCtrl’, function ($scope, $cordovaFileTransfer) {

  $scope.uploadFile = function(files) {
   console.log("selected file "+files);
   // hard coded file path "/android_asset/www/img/ionic.pdf" to be replaced with the user selected file
   $cordovaFileTransfer.upload(restServiceEndpoint, "/android_asset/www/img/ionic.pdf", properties).then(function(result) {
   console.log("SUCCESS: " + JSON.stringify(result.response));
  }, function(err) {
        console.log("ERROR: " + JSON.stringify(err));
   }, function (progress) {
// constant progress updates
  });
});

The problem is that I am not able to get a reference to the selected file. Can someone please help with the steps to achieve this. Thanks!

Hi @ank5

Use this code i hope it will solve your problem

                    var fd = new FormData();			  
		  fd.append("file", fileURI);
		
		  
		 
		  $http.post(url, fd, {
		  
		   withCredentials : false,
		  
		   headers : {
		    'Content-Type' : undefined
		   },
		 transformRequest : angular.identity

		 })
		 .success(function(data)
		 {
			 success(data);
		 })
		 .error(function(data)
		 {	 
	    	alert('Response Error: Check your Internet Connection');
		 });

Thank you Alisax.

Can you please let me know how is the ‘fileURI’ resolved? Is it referring to the file path on the mobile device?

Have you figured out how to achieve this? I’m facing the same issue