I have been struggling to upload a file using Angular JS to POST to my Java Play Framework RESTful backend as a lot of examples I have found don't apply to me.
I am confident my Angular JS code works fine but I will share it anyway:
file-upload.html
<div data-ng-controller="uploadCtrl">
<input type="file" file-model="myFile" id="theFile" name="theFile" />
<button data-ng-click="uploadFile()">Upload</button>
</div>
file-upload-ctrl.js
"use strict";
angular.module("pamm").controller("uploadCtrl", ["$scope", "fileUploadRepository",
function($scope, fileUploadRepository) {
$scope.uploadFile = function () {
var file = $scope.myFile;
console.dir("Ctrl: " + file);
fileUploadRepository.uploadFile(file);
}
}]);
file-upload-repo.js
"use strict";
angular.module("pamm").service("fileUploadRepository", ["$q", "$log", "$rootScope", "contextEvent", "fileUploadDao",
function ($q, $log, $rootScope, contextEvent, fileUploadDao) {
var fileUploadCache = [];
(function init() {
$rootScope.$on(contextEvent.CLEAR_CONTEXT, function clearContext() {
fileUploadCache = [];
$log.info("fileUploadRepository: context cleared");
})
})();
this.uploadFile = function (file) {
var waitingDialog = $$dialog.waiting("Please wait - Uploading file");
var deferred = $q.defer();
fileUploadDao.uploadFile(file).then(function (uploadedFile) {
fileUploadCache.push(uploadedFile);
$log.debug("Repo: " + uploadedFile);
waitingDialog.close();
deferred.resolve(uploadedFile);
}, function (error) {
deferred.reject(error);
waitingDialog.close();
});
return deferred.promise;
};
}]);
The layer up from Repo
"use strict";
angular.module("pamm").service("fileUploadDal", ["$http", "$q", "$log", function ($http, $q, $log) {
this.http = (function serviceCaller() {
return {
/**
* @returns {promise}
*/
POST: function (apiPath, fd) {
var deferred = $q.defer();
$http.post(apiPath, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function (results) {
deferred.resolve(results.data);
}, function (e) {
deferred.reject(e);
});
return deferred.promise;
}
}
})();
$log.info("fileUploadDal:serviceCaller Instantiated");
}]);
Java
Http.MultipartFormData file = request().body().asMultipartFormData();
Where can I go next with this? Hence I can't access the name of the HTML input because of the way my Angular is written.
What can I do to file
to save it the file to a directory I desire.
Thanks,