Skip to content

Instantly share code, notes, and snippets.

@rabbishuki
Created November 21, 2017 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rabbishuki/5971c2a1b1cf863d3af100e79f7ac84b to your computer and use it in GitHub Desktop.
Save rabbishuki/5971c2a1b1cf863d3af100e79f7ac84b to your computer and use it in GitHub Desktop.
Upload a file with angular 1.5
app.controller('myController', function ($scope, Data) {
$scope.uploadFile = function (event) {
var filename = '';
var file = $scope.file;
var uploadUrl = "/fileUpload";
Data.file('upfile.php', file, filename).then(function (newfile) {
// The Result.
});
};
});
// This service connects to our REST API
app.factory("Data", function ($http) {
var serviceBase = 'https://shekel.click/api/v1.2/';
var obj = {};
obj.file = function (q, file, fileName) {
var fd = new FormData();
fd.append('fileToUpload', file);
fd.append('fn', fileName);
fd.append('submit', 'ok');
return $http.post(serviceBase + q, fd, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}).then(function (results) {
return results.data;
});
}
obj.catch = function (method, q, object) {
if (object) console.debug(method.toUpperCase() + ': ' + serviceBase + q + ' with %O', object);
}
return obj;
});
app.directive('fileModel', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.files = {};
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function () {
scope.$apply(function () {
modelSetter(scope, element[0].files[0]);
});
scope.uploadFile();
});
}
};
});
<div class="form-group form-md-line-input">
<label for="file-pic" class="control-label"></label>
<input id="file-pic" type="file" file-model="file" style="display: none;" />
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment