[英]ng-file-upload for image upload not working
我正在尝试使用AngularJS中的ng-file-upload
图像,但它没有正确发生,因为文件相关的属性(如大小和名称)都显示未定义。 我的代码如下:
HTML
<form class="form-horizontal" name="reviewForm" role="form" ng-controller="reviewController" ng-submit="reviewSubmit()" novalidate>
...
<input type="file" id="image" ngf-select ng-model="reviewer.image" name="image" ngf-pattern="image/*" accept="image/*" >
...
JS
angular.module('carApp', ['ngResource', 'ngFileUpload'])
.controller('reviewController', ['$scope', 'updateReviews', 'Upload', function($scope, updateReviews, Upload) {
$scope.reviewSubmit = function() {
alert($scope.reviewer.image.lastModifiedDate);
Upload.upload({
url: 'images',
method: 'POST',
data: { file: $scope.reviewer.image, number: 10 }
}).progress(function(event) {
var progressPercentage = parseInt(100.0 * event.loaded / event.total);
console.log('progress: ' + progressPercentage + '% ' + event.config.data.file.name);
}).success(function(response) {
console.log('Success ' + response.config.data.file.name + 'uploaded. Response: ' + response.data);
}).error(function(error) {
console.log("Error: " + error.message);
});
...
当我检查对象类型(即alert($scope.reviewer.image)
)时,它显示[object File]
,但是当尝试打印名称和大小等时...它总是显示undefined
。 请帮忙!! 我必须在控制器中正确访问图像文件。
请尝试如下所示。这只是图像上传器的工作版本。请根据需要更改属性。
这是工作小提琴
HTML
<body ng-app="fileUpload" ng-controller="MyCtrl">
<form name="myForm">
<fieldset>
<legend>Upload on form submit</legend>
<br>Photo:
<input type="file" ngf-select ng-model="picFile" name="file"
accept="image/*" ngf-max-size="2MB" required
ngf-model-invalid="errorFile">
<i ng-show="myForm.file.$error.maxSize">File too large
{{errorFile.size / 1000000|number:1}}MB: max 2M</i>
<img ng-show="myForm.file.$valid" ngf-thumbnail="picFile" class="thumb">
<br>
<button ng-disabled="!myForm.$valid"
ng-click="uploadPic(picFile)">Submit</button>
<span class="progress" ng-show="picFile.progress >= 0">
<div style="width:{{picFile.progress}}%"
ng-bind="picFile.progress + '%'"></div>
</span>
<span ng-show="picFile.result">Upload Successful</span>
<span class="err" ng-show="errorMsg">{{errorMsg}}</span>
</fieldset>
<br>
</form>
</body>
JS
var app = angular.module('fileUpload', ['ngFileUpload']);
app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
$scope.uploadPic = function(file) {
file.upload = Upload.upload({
url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
data: {username: $scope.username, file: file},
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.