Reputation: 2175
I am developing a file upload module in AngularJS. I will be having multiple file controls and each control can upload one file at a time (not multiple). Finally on click of submit I am saving all the files. I am dynamically generating file controls using ng-repeat
as below.
<div class="upload-button" ng-repeat="fileInput in fileInputs">
<div class="upload-button-icon">
<img src="images/folder-small.png">
<div class="upload-text">{{fileInput}}</div>
<input type="file" file-data="{{fileInput}}" file-model="{{fileInput}}" />
</div>
</div>
JS code to assign values to file controls
$scope.fileInputs = ["Passport","Visa"];
Below is my code to upload files.
myapp.factory('fileUpload', ['$http', function ($http) {
var fileuploadurl = "http://localhost:19144/" + 'api/Customer/UploadLeaseFiles/' + 2;
var service = {
uploadUrl: fileuploadurl,
pendingFiles: [],
doUpload: doUpload
};
return service;
function doUpload() {
debugger;
var files = new FormData();
angular.forEach(this.pendingFiles, function (value, index) {
files.append('file', value);
files.append('IndexValue', index);
});
return $http.post(this.uploadUrl, files, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
})
}
}]);
This is my directive code.
myapp.directive('fileModel', ['fileUpload', function (fileUpload) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.bind("change", function (evt) {
fileUpload.pendingFiles[attrs.fileModel] = evt.target.files[0];
});
}
};
}]);
Above code will work only if I assign integers to fileInputs as:
$scope.fileInputs = [1,2,3];
I am struggling to understand why it is working if I assign integer to fileinputs. How can I assign strings and make the above code work?
Upvotes: 0
Views: 1410
Reputation: 5151
You are pushing files in an array. Basically you are doing something like:
pendingFiles[1] = file
and again
pendingFiles["passport"] = file
The first case works fine with array, but the second won't.
So the solution is change pending files to an object like:
var service = {
uploadUrl: fileuploadurl,
pendingFiles: {},
doUpload: doUpload
};
With object you can make properties on it like:
{
passport : file,
Visa : file2
}
and then use this object while you upload.
Update
for sending extra data use data property of formData obj. Like:
var files = new FormData();
angular.forEach(this.pendingFiles, function (value, index) {
files.append('file', value);
files.append('IndexValue', index);
files.append ('data', angular.toJson(anyJSObject));
});
Hope it works.
Upvotes: 1