//change event
<div class="form-group col-md-6">
<span id="attach">
<input id="uploadFileID" type="file" ng-file-model="files" multiple />
<span class="attach-Text" ng-repeat="file in files">
<span>{{file.name}}</span><a title='Click to Remove' ng-click="removeFile(file, $index)"> X </a>
</span>
</span>
</div>
--------------------------------Controller
$scope.name = 'UploadAttachements';
$scope.files = [];
$scope.removeFile = function (attachedFile, index) {
var removedItem = $scope.files.indexOf(attachedFile);
$scope.files.splice(removedItem, 1);
};
$scope.saveAttachment = function (ListName,ListItemId) {
if ($scope.files.length > 0) {
var numberOfFiles = $scope.files.length;
angular.forEach($scope.files, function (fileValues, key) {
getFileBuffer(fileValues._file)
.then(function (bufferVal) {
uploadFileSP(bufferVal, fileValues._file.name, ListName, ListItemId);
numberOfFiles--;
if (numberOfFiles == 0) {
console.log("attachment insert success");
}
});
});
}
else {
alert('no files');
}
}
function uploadFileSP(bufferVal, fileName, listName, itemID) {
var urlValue = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items(" + itemID + ")/AttachmentFiles/add(FileName='" + fileName + "')";
$.ajax({
url: urlValue,
type: "POST",
data: bufferVal,
async: false,
processData: false,
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"accept": "application/json;odata=verbose",
"content-type": "application/json; odata=verbose"
},
success: fileSuccess,
error: fileError
});
function fileSuccess(data) {
console.log('File Added Successfully.');
}
function fileError(error) {
console.log(error.statusText + "\n\n" + error.responseText);
}
}
function getFileBuffer(file) {
var deferred = $.Deferred();
var reader = new FileReader();
reader.onloadend = function (e) {
deferred.resolve(e.target.result);
}
reader.onerror = function (e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(file);
return deferred.promise();
}
------------------------- add directive-------------------------- app.directive('ngFileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.ngFileModel);
var isMultiple = attrs.multiple;
var modelSetter = model.assign;
element.bind('change', function () {
var values = [];
angular.forEach(element[0].files, function (item) {
var value = {
// File Name
name: item.name,
//File Size
size: item.size,
//File URL to view
url: URL.createObjectURL(item),
// File Input Value
_file: item
};
values.push(value);
});
scope.$apply(function () {
if (isMultiple) {
modelSetter(scope, values);
} else {
modelSetter(scope, values[0]);
}
});
});
}
};
}]);
No comments:
Post a Comment