Uploading files in Ionic application using Web API - angularjs

My issue is as below.
I have given WEB API where I have to add boards picture.
What I have to DO?
User should able to select Image from Phone
User can add Name of board
When user click on submit, entered board name and board image should post using Web API with method of PUT. Here below is WEB API Details
WEB API Details
Header
URL: https://example.com
Content-Type: | Content Type |
Method: PUT
Data
board_id: 321
board_title: | Title |
board_background: | File |
I have used cordovaImagePicker plugin to select image and then I get stuck to uploading it to Server.
I can use cordova file transfer plugin but I think that will not help me in this case as there is no specified place to store image. All the file management done by WEB API, we have to just post file with Data.

After trying a lot solution I have come with below answer.
Board.html
<ion-view>
<ion-nav-bar class="bar">
<ion-nav-title>
<h1 class="title">
Create Board
</h1>
</ion-nav-title>
</ion-nav-bar>
<form name="boardForm" ng-submit="addBoard(data)">
<ion-content padding="false" scroll="true" has-bouncing="false">
<div id="form">
<div style="text-align: center; padding-top: 2%; padding-bottom: 2%;">
<div id="image-preview">
<label for="image-upload" id="image-label"><img src="{{ImagePrefix}}/task_plus.png" alt=""/></label>
<input type="file" name="board_background" id="image-upload" file-model="data.board_background">
</div>
<p>Add Cover</p>
</div>
<ion-list>
<ion-item style="background-color: #F8F8F8;">
<label class="control-label" for="board_name">BOARD NAME</label>
</ion-item>
<ion-item ng-class="{true:'error'}[submitted && boardForm.board_title.$invalid]">
<input type="text" id="board_name" ng-model="data.board_title"
placeholder="Add a Name" name="board_title" required>
<p ng-show="submitted && boardForm.board_title.$error.required">
Please enter a board name
</p>
</ion-item>
</ion-list>
</div>
</ion-content>
<ion-footer-bar>
<button class="button button-block control-button bottomOfPage"
ng-click="submitted = true">
CREATE
</button>
</ion-footer-bar>
</form>
</ion-view>
directive
.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function () {
scope.$apply(function () {
modelSetter(scope, element[0].files[0]);
});
});
}
};
}])
Controller
.controller('ManageBoardCtrl', function ($scope, $http, $ionicPopup, $state, BoardService) {
$scope.submitted = false;
$scope.data = {};
$scope.addBoard = function(formData) {
BoardService.CreateBoard(formData).then(function(response) {
if (response === "success") {
$ionicPopup.alert({
title: "Success",
template: "Board created successfully"
});
}
}, function (response) {
$ionicPopup.alert({
title: "Failed",
template: "Somethings wrong, Can not create boards at now."
});
});
}
})
Service
.service('BoardService', function ($q, $http) {
var getUrl = API_URL + "boards";
var createBoard = function (fData) {
var formData = new FormData();
formData.append("board_title", fData.board_title);
formData.append("board_background", fData.board_background);
return $q(function (resolve, reject) {
$http({
transformRequest: angular.identity,
method: 'POST',
url: getUrl,
headers: { 'Content-Type': undefined },
data: formData
}).success(function (response) {
if (response.success === true) {
resolve('success');
} else {
reject('fail');
}
}).error(function () {
reject('requesterror');
});
});
};
return {
CreateBoard: createBoard
};
})
After deploying application for android / iPhone file selection will handle the browsing Images based on the OS.

One simple thing I can suggest,
Use input["file"] tag to select the image. You will get the file object and a temporary url. with this url you can show the image in the form.
Then use formData to append the image and the other field.
e.g.
var fd = new FormData();
fd.append('board_background', $scope.image, $scope.image.name);
fd.append('board_id', 321);
fd.append('board_title', 'Dummy title');
var xhr = new XMLHttpRequest();
xhr.open('PUT', YOUR_URL, true);
xhr.onload(function(res){
// Write your callback here.
});
// Send the Data.
xhr.send(fd);
Hope it will help you and meet your requirements.

First of all to need to select the image from device.
vm.getImages = function () {
var options = {
quality: 70,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
allowEdit: true,
correctOrientation:true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 300,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: true
};
navigator.camera.getPicture(onSuccess, onFail, options);
function onSuccess(imageURI) {
vm.image = "data:image/jpeg;base64," + imageURI;
vm.imageURI = imageURI;
}
function onFail(message) {
console.log('Failed because: ' + message);
}
};
You can change the source type for input if needed.
sourceType: Camera.PictureSourceType.CAMERA,
On success you get ImageURI either use it directly or convert it to base64 as mentioned below for uploading.
vm.image = "data:image/jpeg;base64," + imageURI;
After this you can use the FileTransfer plugin to upload file and track the progress at the same time.
cordovaFileTransfer.upload()
.then(function (result) {},
function (err) {},
function (progress) {});

Below link will definitely help you:
http://ionicmobile.blogspot.in/2015/10/jquery-file-upload.html
Make the appropriate changes if needed. Any help let me know...

Related

Updating the model with file URL to be saved on submit

I have been able to successfully upload an image with a custom field template calling a function that handles the upload. It then gathers the return url and from there, i have no idea how to insert it back into the field for saving with the form.
Any help would be much appreciated :)
Here is my code:
var myApp = angular.module('myApp', ['ng-admin', 'backand', 'ngFileUpload']);
//myApp.directive('dashboardSummary', require('./dashboards/dashboardSummary'));
myApp.config(['BackandProvider', function(BackandProvider) {
BackandProvider.setAppName('');
BackandProvider.setSignUpToken('');
BackandProvider.setAnonymousToken('');
}]);
myApp.config(function(RestangularProvider) {
// add a response interceptor
RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
var extractedData;
// .. to look for getList operations
if (operation === "getList") {
// .. and handle the data and meta data
extractedData = data.data;
extractedData.meta = data.data.__metadata;
} else {
extractedData = data;
}
return extractedData;
});
});
myApp.config(['NgAdminConfigurationProvider','BackandProvider', function (nga, BackandProvider, $scope) {
// create an admin application
BackandProvider.setAppName('');
BackandProvider.setSignUpToken('');
BackandProvider.setAnonymousToken('');
var admin = nga.application('Pocket Release Admin Manager')
.baseApiUrl('https://api.backand.com/1/objects/'); // main API endpoint#
// Users
var user = nga.entity('users');
user.listView().fields([
nga.field('firstName').isDetailLink(true),
nga.field('lastName'),
nga.field('email')
]);
user.creationView().fields([
nga.field('firstName'),
nga.field('lastName'),
nga.field('email', 'email')
]);
user.editionView().fields(user.creationView().fields());
// add the user entity to the admin application
admin.addEntity(user);
// Platforms
var platforms = nga.entity('platforms');
platforms.listView().fields([
nga.field('id'),
nga.field('platform_name'),
]);
platforms.creationView().fields([
nga.field('id'),
nga.field('platform_name'),
nga.field('platform_id')
]);
platforms.editionView().fields(platforms.creationView().fields());
admin.addEntity(platforms);
var data = {};
// Games
var games = nga.entity('games');
games.listView().fields([
nga.field('id'),
nga.field('game_title').isDetailLink(true),
nga.field('game_url'),
nga.field('platforms', 'reference')
.targetEntity(platforms)
.targetField(nga.field('platform_name'))
.label('Platform')
]);
games.creationView().fields([
nga.field('game_title'),
nga.field('image').template('<img ng-src="{{game_url}}" ng-show="game_url">'),
nga.field('game_url', 'file').uploadInformation({'url':'', 'apifilename':'game_url'}).template('<div ng-controller="main"><label class="btn btn-default btn-file">Browse<input id="fileInput" field="::field" value="entry.values[{{main}}]" entry="entry" entity="::entity" form="formController.form" datastore="::formController.dataStore" type="file" style="display: none;" accept="*/*" ng-click="initUpload()" /></label></div>', true),
nga.field('platforms'),
nga.field('game_description'),
nga.field('game_boxart'),
nga.field('game_release_uk', 'date'),
nga.field('game_release_us', 'date'),
nga.field('game_release_eu', 'date')
]);
games.editionView().fields(games.creationView().fields());
admin.addEntity(games);
// Dash
admin.dashboard(nga.dashboard()
.addCollection(nga.collection(games)
.name('total_games')
.title('Total Games')
.fields([
nga.field('game_title')
])
.sortField('game_title')
.sortDir('DESC')
.order(1)
).template(`
<div class="row dashboard-starter"></div>
<dashboard-summary></dashboard-summary>
<div class="row dashboard-content">
<div class="col-lg-6">
<div class="panel panel-default">
<ma-dashboard-panel collection="dashboardController.collections.total_games" entries="dashboardController.entries.total_games" datastore="dashboardController.datastore"></ma-dashboard-panel>
</div>
</div>
</div>
`));
// Menu Customize
// customize menu
admin.menu(nga.menu()
.addChild(nga.menu(user).icon('<span class="glyphicon glyphicon-file"></span> ')) // customize the entity menu icon
.addChild(nga.menu(games).icon('<span class="glyphicon glyphicon-folder-open"></span> ')) // you can even use utf-8 symbols!
.addChild(nga.menu(platforms).icon('<span class="glyphicon glyphicon-tags"></span> '))
);
// attach the admin application to the DOM and execute it
nga.configure(admin);
}]);
myApp.controller('main', function ($scope, $rootScope, $location, $http, Backand) {
// Image upload stuff
$scope.initUpload = function(){
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(e) {
imageChanged(fileInput);
});
}
function imageChanged(fileInput) {
//read file content
var file = fileInput.files[0];
var reader = new FileReader();
reader.onload = function(e) {
upload(file.name, e.currentTarget.result).then(function(res) {
$scope.imageUrl = res.data.url;
$scope.filename = file.name;
return res.data.url;
}, function(err){
alert(err.data);
});
};
reader.readAsDataURL(file);
};
function upload(filename, filedata) {
// By calling the files action with POST method in will perform
// an upload of the file into Backand Storage
return $http({
method: 'POST',
url : Backand.getApiUrl()+'/1/objects/action/games',
params:{
"name": 'files'
},
headers: {
'Content-Type': 'application/json'
},
// you need to provide the file name and the file data
data: {
"filename": Math.floor(Date.now() / 1000) + ''+ filename.match(/\.[0-9a-z]+$/i),
"filedata": filedata.substr(filedata.indexOf(',') + 1, filedata.length) //need to remove the file prefix type
}
}).success(function(data, status, headers, config) {
//$scope.game_url = data.url;
//$("#game_url").addClass("ng-dirty ng-valid-parse ng-touched").removeClass("ng-pristine ng-untouched");
//$("#game_boxart").val(data.url).addClass("ng-dirty ng-valid-parse ng-touched").removeClass("ng-pristine ng-untouched");
return data.url;
});
};
});
Have you tried making a PUT call to backand in order to save this url in the relevant column?
return $http({
method: 'PUT',
url : Backand.getApiUrl()+'/1/objects/games/YOUR_GAME_ID',
headers: {
'Content-Type': 'application/json'
},
data: {
urlColumn:imageUrl
}
}).success(function(data, status, headers, config) {
.....
});

How to disable buttons until http request is processed/loaded in AngularJS?

I want to write a directive that keeps a button and page disabled for the duration of the http request.
If I update or submit a form, the button will disable until the http
response is complete.
When a page is loading, it will disable until the entire data is
loaded from the server.
After 10 seconds, the button will be active and the user can click
multiple times.
app.js
<script>
var angModule = angular.module("myApp", []);
angModule.controller("myCtrl", function ($scope, $timeout) {
$scope.isSaving = undefined;
$scope.btnVal = 'Yes';
$scope.save = function()
{
$scope.isSaving = true;
$timeout( function()
{
$scope.isSaving = false;
}, 1000);
};
});
</script>
index.html
<div ng-app="myApp">
<ng-form ng-controller="myCtrl">
Saving: {{isSaving}}
<button ng-click="save()" ng-disabled="isSaving">
<span ng-hide="isSaving">Save</span>
<span ng-show="isSaving">Loading...</span><i class="fa fa-spinner fa-spin" ng-show="isSaving"></i>
</button>
</ng-form>
</div>
I am new to AngularJS, please help me write a directive for this.
here a basic example :
<button ng-click="save()" loading="Loading..." notloading="save" disableonrequest>
myApp.directive("disableonrequest", function($http) {
return function(scope, element, attrs) {
scope.$watch(function() {
return $http.pendingRequests.length > 0;
}, function(request) {
if (!request) {
element.html("<span >"+attrs.notloading+"</span>");
} else {
element.html("<span >"+attrs.loading+"</span><i class='fa fa-spinner fa-spin'></i>");
}
});
}
});
A WORKING EXAMPLE
Depending on your needs, you may not necessarily need a custom directive for this simple task.
You can simply set the $scope.isSaving property inside the callback for $http.
For example
$http({
url: 'http://path/to/the/api/',
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
}
})
.success(function(data, status){
$scope.isSaving = false;
})
.error(....);

AngularJS Upload and Post Multiple Files

So ultimately, what I'm doing is trying to upload and post multiple files to a Django backend using AngularJS. I can post a single file, but it seems like when a FileList object is put in the $http.post data field, the backend no longer detects any files in the POST request.
Here's what the html looks like:
<form enctype="multipart/form-data" action="upload" method="POST">
<div class="form-group">
<span class="btn btn-info btn-file">
<i class="glyphicon glyphicon-file"></i> Browse
<input class="btn btn-lg btn-info" name="uploadedfile" type="file" accept=".eossa" onchange="angular.element(this).scope().filesUploaded(this.files)" multiple><br/>
</span>
<button type="button" class="btn btn-success" ng-click="uploadFiles()" ng-class="{'disabled':!model.files.length}">
<i class="glyphicon glyphicon-download-alt"></i> Submit
</button>
</div>
<pre ng-repeat="file in model.files" ng-show="file.name">{{file.name}} ({{file.size/1000}} KB) {{file.lastModifiedDate}} </pre>
</form>
And here's the relevant JavaScript:
$scope.filesUploaded = function(files) {
if(files.length < 1) return;
$scope.model.files = files;
$scope.$apply();
};
$scope.uploadFiles = function(){
var fd = new FormData();
fd.append("file", $scope.model.files);
Services.uploadFiles(fd)}
Here's my uploadFiles service:
uploadFiles: function(form){
return $http.post("/api/file-upload/", form, {withCredentials: true, headers: {'Content-Type': undefined }, transformRequest: angular.identity})
},
The backend does not see anything in the request.FILES in this case; however, if instead of appending $scope.model.files, I append $scope.model.file[0], I do see a file in the request on the backend. In which case, the uploadFiles function looks like this:
$scope.uploadFiles = function(){
var fd = new FormData();
fd.append("file", $scope.model.files[0]);
Services.uploadFiles(fd)
}
So why can't one append a FileList to a Form? How can you POST a FileList?
Thanks
First create a directive as pointed out here
.directive('filesModel', function () {
return {
restrict: 'A',
controller: function ($parse, $element, $attrs, $scope) {
var exp = $parse($attrs.filesModel);
$element.on('change', function () {
exp.assign($scope, this.files);
$scope.$apply();
});
}
};
});
And for the transform function, check this out.
You can use a factory like:
.factory('File', function () {
return {
// Define a function to transform form data
transformRequest: function (data, headersGetter) {
var fd = data ? new FormData() : null;
if (data) {
angular.forEach(data, function (value, key) {
// Is it a file?
if (value instanceof FileList) {
if (value.length == 1) {
fd.append(key, value[0]);
} else {
angular.forEach(value, function (file, index) {
fd.append(key + '_' + index, file);
});
}
}
// Is it an object?
else if (typeof value === 'object') {
fd.append(key, JSON.stringify(value));
} else {
fd.append(key, value);
}
});
}
return fd;
}
};
})
Then for the service:
uploadFiles: function(form){
return $http.post("/api/file-upload/", form, {withCredentials: true, headers: {'Content-Type': undefined }, transformRequest: File.transformRequest})
}
Finally the html:
<input type="file" files-model="<model>"/>
Or this for multiple files
<input type="file" files-model="<model>" multiple/>
I've never tried the method above and this may be a cop out but I thought I would turn you on to some libraries.
I would checkout these two awesome AngularJS file upload Repos. I personally use this one.
Both support easy setup multiple file upload.
ng-file-upload
Here's another.
angular-file-upload
Why put in hours of work when dozens of folks have contributed and done it for you?

MEAN Stack: How to bind uploads to a mongoose model?

I´m playing around with upload forms in my MEAN Application (its a project control panel). I used this tutorial for implementing a working upload: http://markdawson.tumblr.com/post/18359176420/asynchronous-file-uploading-using-express-and
With this I can upload files - they appear in my upload folder.
Now I want to achieve, that the upload is linked to the project the user made. E.g.: Jon Doe is logged in, he uploads a picture. Now I want to render his profile page. I query my project model for Jon Doe --> now I want to media files uploaded by him.
So how do I post my media, to the projectSchema of Jon Doe? Afterwards, whats the best way to display all the media in Angular?
------Edit------
I´ve been trying aroud with the extension multer, and I nearly managed to make GET and POST of uploads working. Problem is, I cant fetch any data from the database. My Console gives me a GET /uploads/media/[object%20Object] 304.
The target is: Writing the project_id, with the files to the mediaSchema. So when I´m opening a project, I get all media matching the project_id of this Project. I updated my code for you:
HTML Form
<form id="uploadForm"
enctype="multipart/form-data"
action="/uploads/"
method="post">
<label for="project_id">Ihre Projekt ID</label>
<input type="text" name="project_id" value="{{projects._id}}" readonly>
<input type="file" name="userPhoto"/>
<button type="submit">Hochladen</button>
</form>
<hr>
<img ng-src="{{media.img}}"/>
Angular Controller
var app = angular.module('myApp', []);
var projectId =
app.controller('projectCtrl', function($scope, $http) {
$scope.myVar = false;
$scope.toggle = function() {
$scope.myVar = !$scope.myVar
};
$http.get('/profile/project/').then(function (res){
$scope.projects = res.data;
var projectId = $scope.projects._id;
});
//GET Media
$http.get('/uploads/media/'+projectId).then(function(data){
console.log('Medien-Daten erhalten');
$scope.media = data;
});
});
Routing:
//FILE HANDLING FOR PROJECTMEDIA
var Media = require('./models/media.js');
//GET all the media
app.get('/uploads/', function(req, res, next){
Media.find(function (err, media){
if (err) return next (err);
res.json(media);
});
});
//GET one item
app.get('/uploads/media/:projectId', function(req, res, next){
Media.findOne(req.params , function (err, media){
if (err) return next (err);
res.json(media);
});
});
mediaSchema
var mongoose = require ('mongoose');
var mediaSchema = mongoose.Schema({
img : {data: Buffer, contentType: String},
project_id : String,
updated_at : {type: Date, default: Date.now }
});
projectSchema
var projectSchema = mongoose.Schema({
author : String,
name : String,
description : String,
tags : String,
updated_at : {type: Date, default: Date.now },
active : {type: Boolean, default: false}
});
To answer your questions.
how do I post my media, to the projectSchema of Jon Doe?
In Angular you want to use the $http service. It's very simple, an example for you would be.
HTML
<input id="filebutton" name="filebutton" file-model="myFile" class="input-file" type="file">
<br>
<button ng-click="postForm()" id="singlebutton" name="singlebutton" class="btn btn-primary">Upload</button>
APP
var app = angular.module('jsbin', []);
//we need to use this directive to update the scope when the input file element is changed.
app.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
//use a service to handle the FormData upload.
app.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('userPhoto', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
//all done!
})
.error(function(){
});
};
}]);
app.controller('DemoCtrl', function($scope, $http, fileUpload) {
$scope.postForm = function(){
console.log($scope.myFile);
// Run our multiparty function.
fileUpload.uploadFileToUrl($scope.myFile, '/upload/');
};
});
Afterwards, whats the best way to display all the media in Angular?
Assuming you have your endpoint working correctly. You can do a $http only this time do a get.
JS
// make the request
$http.get('/your/media').then(function(response){
//add to scope
$scope.myMedia = response.data;
});
HTML
<div ng-repeat="photo in myMedia">{{photo}}</div>

Ionic-Angular.js Taking pictures & sending to server: null images

So I have managed to use a custom directive to upload images to my server, through Angular.js.
I have also managed to implement the camera functionality from Cordova.
Now I am trying to connect the two, but when sending images to the server, they get stored as null. I believe the problem lies in the fact that I was using an input field to get the image, and it was getting the full Object, and now I am getting just the image path after I take the picture and send it. My problem is, I don't really understand how I could convert the path to an Object, IF that is the problem?
index.html
<form class="form-horizontal" role="form">
<button class="picButton" ng-click="getPhoto()" class="button button-block button-primary">Take Photo</button>
<img ng-src="{{lastPhoto}}" style="max-width: 100%">
...
</form>
controllers.js
$scope.getPhoto = function() {
Camera.getPicture().then(function(imageURI) {
console.log(imageURI);
$scope.lastPhoto = imageURI;
$scope.upload(); <-- call to upload the pic
},
function(err) {
console.err(err);
}, {
quality: 75,
targetWidth: 320,
targetHeight: 320,
saveToPhotoAlbum: false
});
};
$scope.upload = function() {
var url = '';
var fd = new FormData();
//previously I had this
//angular.forEach($scope.files, function(file){
//fd.append('image',file)
//});
fd.append('image', $scope.lastPhoto);
$http.post(url, fd, {
transformRequest:angular.identity,
headers:{'Content-Type':undefined
}
})
.success(function(data, status, headers){
$scope.imageURL = data.resource_uri; //set it to the response we get
})
.error(function(data, status, headers){
})
}
When printing $scope.lastPhoto I get the image path: file:///var/mobile/Applications/../tmp/filename.jpg
EDIT
Request Headers:
------WebKitFormBoundaryEzXidt71U741Mc45
Content-Disposition: form-data; name="image"
file:///var/mobile/Applications/C65C8030-33BF-4BBB-B2BB-7ECEC86E87A7/tmp/cdv_photo_015.jpg
------WebKitFormBoundaryEzXidt71U741Mc45--
Should this causing the problem? Since I can see I am sending the path but not the image itself..
Before changing, I was using a custom directive, and was using $scope.files to append to my request in the upload function:
<input type="file" file-input="files" multiple onchange="angular.element(this).scope().filesChanged(this);upload();">
<button ng-click="upload()">Upload</button>
I resolve with this code :
$scope.getPhoto = function() {
navigator.camera.getPicture(onSuccess, onFail, { quality: 75, targetWidth: 320,
targetHeight: 320, destinationType: 0 });
//destination type was a base64 encoding
function onSuccess(imageData) {
//preview image on img tag
$('#image-preview').attr('src', "data:image/jpeg;base64,"+imageData);
//setting scope.lastPhoto
$scope.lastPhoto = dataURItoBlob("data:image/jpeg;base64,"+imageData);
}
function onFail(message) {
alert('Failed because: ' + message);
}
}
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++)
{
ia[i] = byteString.charCodeAt(i);
}
var bb = new Blob([ab], { "type": mimeString });
return bb;
}
after this use append to your formdata like this:
formData.append('photo', $scope.lastPhoto, $scope.publish.name+'.jpg')
This code run on IOS without problem.
I think your problem lies in the 'Content-Type':undefined. For images, you should use 'Content-Type':'image/jpeg'.
I would also add enctype="multipart/form-data" to the <form>.
What I ended up doing was to add destinationType: Camera.DestinationType.DATA_URL in the options of the getPhoto function, and that returns a base64 representation of the image, which I then send over to the server and store in a TextField() (Django):
$scope.getPhoto = function() {
Camera.getPicture().then(function(imageURI) {
console.log(imageURI);
$scope.lastPhoto = imageURI;
$scope.upload(); <-- call to upload the pic
},
function(err) {
console.err(err);
}, {
quality: 75,
targetWidth: 320,
targetHeight: 320,
saveToPhotoAlbum: false,
destinationType: Camera.DestinationType.DATA_URL
});
};
Also, when deadling with Base64 images, remember to call the using:
<img ng-src="data:image/jpeg;base64,{{image}}" />

Resources