Вот мой код для загрузки файла на сервер при изменении ввода
$scope.uploadImage = function (f) {
$http.post('/art',{'image':f},{headers: {'Content-Type': undefined}}).then(function (response) {
console.log(response);
});
}
но я получу пустые файлы на сервере, но я проверю свой код сервера с нормальной файловой загрузкой, он отлично работает без каких-либо проблем
Serverside
//get empty in angular upload
console.log(req.file('image'));
req.file('image').upload({
// don't allow the total upload size to exceed ~10MB
maxBytes: 10000000
},function whenDone(err, uploadedFiles) {
return res.json({
'status':uploadedFiles
})
});
HTML
<input type="file" ng-model="art.artImage" onchange="angular.element(this).scope().uploadImage(this.files)" name="artImage" id="artImage">
Я считаю, что его проблема с content-type
в угловом почтовом запросе
Используйте ng-fileUpload
lib для angularjs
Мой HTML
<form method="post" enctype="multipart/form-data" ng-controller="commentCtrl" name="form">
<a href="" type="file" class="custom-height"><img src="source/assets/images/icons/icofileattached.png" class="attachmentpng-height" ngf-select="uploadFiles($file)" ng-model="files"/></a>
<md-button type="submit" class="md-raised custom-submit-button" ng-click="MakeComments()"> SUBMIT </md-button>
</form>
Код моего контроллера
$scope.uploadFiles = function(file) {
console.log(file);
$scope.fileData = file;
var fd = new FormData();
fd.append('file', file);
Restangular.one('/api/files/end points').withHttpConfig({transformRequest: angular.identity})
.customPOST(fd, '', undefined, {'Content-Type': undefined})
};
Попробуйте это, не используйте onload в теге HTML для файла:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body ng-app = "myApp">
<div ng-controller = "myCtrl">
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.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]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
alert("Done");
})
.error(function(){
alert("Sorry");
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "/art";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
</script>
</body>
</html>
Когда тип ввода file
файл не будет прикрепить модель. Вам нужно обходное решение, подобное этому.
.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
var reader = new FileReader();
reader.onload = function (loadEvent) {
scope.$apply(function () {
scope.fileread = loadEvent.target.result;
});
}
reader.readAsDataURL(changeEvent.target.files[0]);
});
}
}
}]);
измените ввод как
<input type="file" fileread="art.artImage" onchange="angular.element(this).scope().uploadImage(this.files)"
name="artImage" id="artImage">
используйте multipart
заголовок в запросе
$http.post('/art', {
'image': art.artImage
}, {
transformRequest: angular.identity,
headers: {
'Content-Type': "multipart/form-data"
}
})
1 0 : File lastModified : 1493977671608 lastModifiedDate : Fri May 05 2017 15:17:51 GMT+0530 (IST) __proto__ : Object name : "1493977658097.jpeg" size : 10286 type : "image/jpeg" webkitRelativePath : "" __proto__ : File