Issues Posting Camera Pictues to the server (django rest framework ) From Ionic


#1

I am completely new to “ionic”,“Angular JS” and
"django-restframework", So in the course of building my first
application i am experiencing these issues highlighted below.

I have the camera and file transfer plugin installed in my appI implemented the camera function successfully, i installed the apk
(debug release) after running ionic build android, and it
accesses the camera and takes the picture on the mobile device (Samsung) that it was installed on.However, the problem i am facing is about posting the camera image
to
my back end (django-restframework), i suspect the “http POST” request is
somehow being transformed into a GET request which prevents the image
from
uploading …because i get a reference to all objects contained in that
database when i inspect with chrome which typically should be the case
if i issue a simple get request as i am using DRF’s modelviewset,
Please can anyone help me with this?? i have being at
it for over two weeks , still no solution in sight.

my app.js code
`angular.module(‘starter’, [‘ionic’, ‘starter.controllers’, ‘starter.services’, ‘ngCordova’])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {

if(window.cordova && window.cordova.plugins.Keyboard) {
  // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
  // for form inputs)
  cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);

  // Don't remove this line unless you know what you are doing. It stops the viewport
  // from snapping when text inputs are focused. Ionic handles this internally for
  // a much nicer keyboard experience.
  cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
  StatusBar.styleDefault();


   }
  });
})

.config(function($stateProvider, $urlRouterProvider,$compileProvider, $httpProvider) {
$httpProvider.defaults.withCredentials = true;
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
 $stateProvider
  // setup an abstract state for the tabs directive
    .state('app', {
    abstract:true,
    url: '/app',   
    templateUrl: 'templates/app.html'
  })

  .state('app.welcome', {
      url: '/welcome',    
      views: {
        'welcome': {
          templateUrl: 'templates/welcome.html',        
        }
      }
    })
  .state('app.news', {
      url: '/news',   
      views: {
        'welcome': {
          templateUrl: 'templates/news.html',
          controller: 'homeCtrl'
        }
      }
    })
  .state('app.vendor', {
      url: '/vendor',     
      views: {
        'welcome': {
          templateUrl: 'templates/vendor.html',
          controller: 'homeCtrl'
        }
      }
    })

  .state('app.map', {
      url: '/map',
      cache:false,
      views: {
        'welcome': {

      templateUrl: 'templates/map.html',
      controller: 'mapCtrl'
    }
  }
})`

And here is the controller.js Code for the camera and filetransfer
$scope.imagereport = {
imagelist:[],
addimage :function(){
var nt = $scope.imagereport;
$ionicActionSheet.show({
buttons: [
{ text: ‘From Camera’ },
{text:‘From Gallery’}
],

        titleText: 'Supporting Pictures',
        cancelText: 'Close',       
        buttonClicked: function(index) {
            if(index === 0) {       
            $scope.addimages(1);
            }
            else{
                $scope.addimages(2);
                }

        }

    });
    }
    };


$scope.addimages =function(eve) {   
$scope.imgo;          
  var options = {
     quality : 75,
      destinationType: 1,
     targetWidth: 200,
     targetHeight: 200,
     sourceType:eve,
     correctOrientation:true,
     saveToPhotoAlbum: false,

        encodingType: 0     // 0=JPG 1=PNG
  };

  Camera.getPicture(options).then(function(imageData) {         
         var obj = imageData;   
         $scope.imagetaken.push(obj); 
         $scope.imgo =imageData;
         var opt = {
         fileKey : "file",
         fileName :fileURL.substr(imageData.lastIndexOf('/') + 1),
         chunkedMode :false,
         mimeType : "image/jpeg", 
         headers :{ Connection:"close", 'CONTENT-TYPE':'application/json', Vary:'Accept' ,'Access-Control-Allow-Headers': 'x-requested-with' },
         //popoverOptions: CameraPopoverOptions,
         saveToPhotoAlbum: false        
        };
        var url = "http://riwama.sites.djangoeurope.com/addtemprorarypicapi"
       $cordovaFileTransfer.upload( encodeURI("http://riwama.sites.djangoeurope.com/addtemprorarypicapi"),imageData, opt).then(    
       function(result){
        console.log('Success: ' +JSON.stringify(result));       
        $.each(result,function(){
        $.each(this,function(k,v){
        var did = k;
        $scope.ids.push(did);
        });
        });
        var im = $scope.imagetaken;
        $scope.imagetaken.push(imageData);          
            },
         function(err){          
            alert('can not upload image because: ' +JSON.stringify(err));
            console.log(err)        
            },
            function (progress) {
            $timeout(function () {
          $scope.upProgress = (progress.loaded / progress.total) * 100;
           });
        });
      }, function(err) {
         console.log(err);      
      });

here is the view implementing Django rest Framework’s Modelviewset

from .models import *
from rest_framework import permissions
from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import detail_route,parser_classes
from rest_framework.parsers import MultiPartParser, FormParser,FileUploadParser
from rest_framework import mixins
from rest_framework.permissions import AllowAny
from rest_framework import generics
from .drf_serializers import temprorary_ser
restapi_permission_classes = (AllowAny,)


class addtemprorarypicapi(ModelViewSet):
    queryset = temprorary_report_pic.objects.all()
    serializer_class = temprorary_ser 
    #permission_classes = (AllowAny,)
    parser_classes = (MultiPartParser,FormParser,FileUploadParser,)
    def perform_create(self, serializer):        
        serializer.save(Picture=self.request.data.get('file'))

I have CORS Installed on django and the settings are thus
CORS_URLS_REGEX = '^.*$'
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_HEADERS = (
‘x-requested-with’,
‘content-type’,
‘accept’,
‘origin’,
‘authorization’,
‘accept-encoding’,
‘x-csrftoken’
)
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_METHODS = ( ‘GET’, ‘POST’, ‘PUT’, ‘PATCH’, ‘DELETE’, ‘OPTIONS’ )
CORS_ALLOW_CREDENTIALS = True