Created
November 21, 2017 13:29
-
-
Save rabbishuki/5971c2a1b1cf863d3af100e79f7ac84b to your computer and use it in GitHub Desktop.
Upload a file with angular 1.5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}); | |
} | |
}; | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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