我正在尝试使用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
。请帮忙!!我必须在控制器中正确访问图像文件。
答案 0 :(得分:0)
Please try as shown below.This is just a working version of image uploader.Please change the properties as you wish.
This is the working Fiddle
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));
});
}
}]);