I have an html upload form and an angular controller controlling it. In the controller, I found out how to get the files uploaded but my question is how can I move/upload these files to the server? I checked out multer but I don't believe this is going to work in my case because I can't require it in the client-side. Here is what my controller currently looks like:
app.controller('uploadCtrl', function($scope, $location, $http){
$scope.enableSubmitButton = false;
$scope.fileSizeError = false;
var selectedFiles = [];
//get files selected
$scope.getFiles = function($files){
selectedFiles = $files;
//display upload button if there is a valid file to upload
if(selectedFiles.length !== 0){
$scope.enableSubmitButton = true;
}
}
$scope.upload = function(){
if($scope.enableSubmitButton){
//disable to prevent clicking again
$scope.enableSubmitButton = false;
//correctly shows the file data
console.dir(selectedFiles);
//upload files to server
//What should I do here?
}
}
});
Here is an example
Step:1 Initialize Your app
var myApp = angular.module('myApp', []);
Step:2 Make a directive named fileModel
. it can use link funtion and bind change
property so that if a file upload, change function executes and then set model scope
with files object.simple it parses file object
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A', //define attribute
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]);
});
});
}
};
}]);
Step:3 Make a fileUpload service
so that transfer file to server using $http
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData(); //FormData
fd.append('file', file); //file object
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined} //define req headers
})
.success(function(){
})
.error(function(){
});
}
}]);
Step:4 use fileUpload service
and call its uploadFileToUrl
function and pass file object and url for
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){ //uploadFile function
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.