Click here to Skip to main content
15,896,269 members
Articles / Web Development / HTML
Tip/Trick

File Upload Using AngularJS and ASP.NET MVC5

Rate me:
Please Sign up or sign in to vote.
4.79/5 (18 votes)
21 Feb 2015CPOL2 min read 209.6K   7.1K   24   46
How to upload file using AngularJS and ASP.NET MVC5? How to upload multiple files using AngularJs and MVC5?

What's This?

The goal of this is as given in the title. It's very simple. Here, I will document the simplest way to upload file using AngularJs and ASP.NET MVC5.

Why is This?

There are so many libraries to do this online. So, what difference will I make? If this question comes to your mind at the very beginning, then cool! Let's have a look at why you must be bothered about this.

My requirement is very simple. I have a Model. Please see below:

C#
public class TutorialModel
    {
        public string Title { get; set; }
        public string Description { get; set; }
        public HttpPostedFileBase Attachment { get; set; }
    }

I want to bind this model from client side with Angular and post it to the ASP.NET MVC5 controller.

Most of the libraries that I found online work in the following way:

  1. Upload file --> Save it --> Return the file URL in response
  2. Send another request with model and file URL

The common problem of this way is: every time you change the file, it will upload the file to the server. Previous files will not be deleted. So I don't want to do this and maybe even you might not want it. I will show how we can do it in one request. Users are free to change anything as many times as they wish. When they will click save, then the Model will be sent to the server.

Form

How is This?

To do this, I will use HTML5 FormData here. I have written a separate Angular module for this so that anyone can use it in their module. Let's have a look in my akFileUploader module.

Download from github.

JavaScript
(function () {

    "use strict"

    angular.module("akFileUploader", [])

           .factory("akFileUploaderService", ["$q", "$http",
               function ($q, $http) {

                   var getModelAsFormData = function (data) {
                       var dataAsFormData = new FormData();
                       angular.forEach(data, function (value, key) {
                           dataAsFormData.append(key, value);
                       });
                       return dataAsFormData;
                   };

                   var saveModel = function (data, url) {
                       var deferred = $q.defer();
                       $http({
                           url: url,
                           method: "POST",
                           data: getModelAsFormData(data),
                           transformRequest: angular.identity,
                           headers: { 'Content-Type': undefined }
                       }).success(function (result) {
                           deferred.resolve(result);
                       }).error(function (result, status) {
                           deferred.reject(status);
                       });
                       return deferred.promise;
                   };

                   return {
                       saveModel: saveModel
                   }}])
         .directive("akFileModel", ["$parse",
                function ($parse) {
                    return {
                        restrict: "A",
                        link: function (scope, element, attrs) {
                            var model = $parse(attrs.akFileModel);
                            var modelSetter = model.assign;
                            element.bind("change", function () {
                                scope.$apply(function () {
                                    modelSetter(scope, element[0].files[0]);
                                });
                            });
                        }
                    };
                }]);
})(window, document);

I will give you a very brief description of what this module does. It has one directive and one factory service.

  • akFileModel directive: It is responsible for changing file and binding it to the modelSetter.
  • akFileUploaderService: It basically creates FormData objects and sends it to the desired URL using $http.

Use in MVC

application.js

JavaScript
"use strict";
(function () {
    angular.module("application", ["ngRoute", "akFileUploader"]);
})();

template

HTML
<form class="form-horizontal">
    <h4>Tutorial</h4>
    <hr />
    <div class="form-group">
        <label for="title" class="col-md-2 control-label">Title</label>
        <div class="col-md-10">
            <input type="text" data-ng-model="tutorial.title" 
            name="title" class="form-control" />
        </div>
    </div>
   <div class="form-group">
        <label for="description" class="col-md-2 control-label">Description</label>
        <div class="col-md-10">
            <textarea data-ng-model="tutorial.description" 
            name="description" class="form-control">
            </textarea>
        </div>
    </div>
   <div class="form-group">
        <label for="attachment" class="col-md-2 control-label">Attachment</label>
        <div class="col-md-10">
            <input type="file" name="attachment" 
            class="form-control" data-ak-file-model="tutorial.attachment" />
        </div>
    </div>
  <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="button" class="btn btn-primary" 
            value="Save" data-ng-click="saveTutorial(tutorial)" />
        </div>
    </div>
</form>

service

JavaScript
"use strict";
(function () {
    angular.module("application")
           .factory("entityService", 
           ["akFileUploaderService", function (akFileUploaderService) {
               var saveTutorial = function (tutorial) {
                   return akFileUploaderService.saveModel(tutorial, "/controllerName/actionName");
               };
               return {
                   saveTutorial: saveTutorial
               };
           }]);
})();

controller(js)

JavaScript
"use strict";
(function () {
    angular.module("application")
           .controller("homeCtrl", ["$scope", "entityService",
               function ($scope, entityService) {
                   $scope.saveTutorial = function (tutorial) {
                       entityService.saveTutorial(tutorial)
                                    .then(function (data) {
                                        console.log(data);
                                    });
                   };
               }]);
})();

MVC Controller Action

C#
[HttpPost]
public ActionResult SaveTutorial(TutorialModel tutorial)
    {
        return Json("Tutorial Saved",JsonRequestBehavior.AllowGet);
    }

Uploading Multiple files

In order to upload multiple files, You have to change something. In input field, allow multiple.

HTML
<input type="file" name="attachment" class="form-control" 
data-ak-file-model="tutorial.attachment" multiple />

In akFileUploader module, update the getModelAsFormData of akFileUploaderService.

JavaScript
var getModelAsFormData = function (data) {
                       var dataAsFormData = new FormData();
                       angular.forEach(data, function (value, key) {
                           if (key == "attachment") {
                               console.log(value);
                               for (var i = 0; i < value.length; i++) {
                                   dataAsFormData.append(value[i].name, value[i]);
                               }
                           } else {
                               dataAsFormData.append(key, value);
                           }
                       });
                       return dataAsFormData;
                   };

Here, I have appended all files in form data by attachment key. You will notice that my input name is attachment. So if you change it, then keep the same name in getModelAsFormData as well.

JavaScript
modelSetter(scope, element[0].files);

Write the above line instead of following in akFileModel directive:

JavaScript
modelSetter(scope, element[0].files[0]);

Now receive the files in controller in the following way...

C#
[HttpPost]
       public ActionResult SaveTutorial(TutorialModel tutorial)
       {
           foreach (string file in Request.Files)
           {
               var fileContent = Request.Files[file];
               if (fileContent != null && fileContent.ContentLength > 0)
               {
                   var inputStream = fileContent.InputStream;
                   var fileName = Path.GetFileName(file);
                   var path = Path.Combine(Server.MapPath("~/App_Data/Images"), fileName);
                   using (var fileStream = System.IO.File.Create(path))
                   {
                       inputStream.CopyTo(fileStream);
                   }
               }
           }
           return Json("Tutorial Saved",JsonRequestBehavior.AllowGet);
       }

So I am done. Start using it. Thanks!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Instructor / Trainer Jashore University of Science and Technology
Bangladesh Bangladesh
2016 Microsoft MVP

Currently, I am devoted to provide technical and development support to the SharePoint clients and also I am working on angularjs. I am experienced with C#, ASP.NET, SharePoint, SignalR, angularjs, MS SQL, Oracle 11g R2, Windows Phone, Firefox OS and so on. I have fallen in love with many technologies but never got married to any of them. I am evolving myself as full stack developer. I always like to share knowledge as much as to gather from you.

Comments and Discussions

 
QuestionSave files to local folder Pin
Klent Diamond1-Jan-18 16:20
Klent Diamond1-Jan-18 16:20 
QuestionThank you! It work for me. Can someone recommend me "ng packages" who do this also? Pin
blaskxx28-Mar-17 6:32
blaskxx28-Mar-17 6:32 
QuestionThe Demo can't run Pin
Member 1287564130-Nov-16 16:15
Member 1287564130-Nov-16 16:15 
AnswerRe: The Demo can't run Pin
Atish Dipongkor1-Dec-16 23:56
professionalAtish Dipongkor1-Dec-16 23:56 
QuestionUpload File using Angular JS Pin
Member 1260705327-Jun-16 18:08
Member 1260705327-Jun-16 18:08 
AnswerRe: Upload File using Angular JS Pin
Atish Dipongkor28-Jun-16 1:13
professionalAtish Dipongkor28-Jun-16 1:13 
GeneralRe: Upload File using Angular JS Pin
Member 1260705328-Jun-16 19:06
Member 1260705328-Jun-16 19:06 
QuestionUsing this we can able to upload more than 2 gb file (any extension) Pin
Member 822666524-Jun-16 5:14
Member 822666524-Jun-16 5:14 
QuestionURL? Pin
Member 1259426220-Jun-16 8:44
Member 1259426220-Jun-16 8:44 
AnswerRe: URL? Pin
Atish Dipongkor20-Jun-16 20:28
professionalAtish Dipongkor20-Jun-16 20:28 
GeneralRe: URL? Pin
Member 1259426221-Jun-16 2:00
Member 1259426221-Jun-16 2:00 
QuestionYou don't need file stream Pin
Aximili15-Jun-16 15:34
professionalAximili15-Jun-16 15:34 
AnswerRe: You don't need file stream Pin
Atish Dipongkor16-Jun-16 1:24
professionalAtish Dipongkor16-Jun-16 1:24 
QuestionFile not get in webapi Pin
puneet kankar3-Feb-16 19:09
puneet kankar3-Feb-16 19:09 
AnswerRe: File not get in webapi Pin
Atish Dipongkor3-Feb-16 19:53
professionalAtish Dipongkor3-Feb-16 19:53 
QuestionNullable decimal properties don't validate Pin
Member 1175819923-Jan-16 6:18
Member 1175819923-Jan-16 6:18 
QuestionGetting Error as Unsupported Media Content Pin
magesh venkatesan16-Jan-16 17:16
magesh venkatesan16-Jan-16 17:16 
Hi,

I am following the same pattern to upload the file and below is my code. For some reason I am getting the error as below.

Any help would be appreciated, it is not hitting the breakpoint in the mvc controller post. When I tried to capture the formdata before the post call, it does not have any data in formdata(console.log(dataAsFormData); -- This does not have any data in it). but has the data in the object that is assigned to formdata(console.log(key + " : " + value); -- this is printing the data as expected sent from the contentupload.cshtml).

Console.log added in the below function to debug :

var getModelAsFormData = function (data) {
console.log(data);
var dataAsFormData = new FormData();
angular.forEach(data, function (value, key) {
console.log(key + " : " + value);
dataAsFormData.append(key, value);
});
console.log(dataAsFormData);
return dataAsFormData;
};



Error:

{
"$id": "1",
"message": "The request entity's media type 'multipart/form-data' is not supported for this resource.",
"exceptionMessage": "No MediaTypeFormatter is available to read an object of type 'DocumentumRequestCreateModel' from content with media type 'multipart/form-data'.",
"exceptionType": "System.Net.Http.UnsupportedMediaTypeException",
"stackTrace": " at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"
}

Model :

namespace EmployeeToolkit.Services.Models.Documentum
{
#region Usings

using System;
using System.Net.Http;
using System.Web;

#endregion

public class DocumentumRequestCreateModel
{
/// <summary>
/// Initializes a new instance of the <see cref="DocumentumRequestCreateModel" /> class.
/// </summary>
public DocumentumRequestCreateModel()
{
this.CreationDate = DateTime.Now;

this.EffectiveDate = DateTime.Now;

this.ExpirationDate = DateTime.Now;

this.Watermark = false;
}

/// <summary>
/// Gets or sets the Documentum Object Name (Object_name).
/// </summary>
/// <value>
/// The Documentum Object Name.
/// </value>
public string DocumentumName
{
get;
set;
}

/// <summary>
/// Gets or sets the Documentum Identifier(r_object_id).
/// </summary>
/// <value>
/// The Documentum Identifier.
/// </value>
public string DocumentumIdentifier
{
get;
set;
}

/// <summary>
/// Gets or sets the Documentum title.
/// </summary>
/// <value>
/// The title.
/// </value>
public string Title
{
get;
set;
}

/// <summary>
/// Gets or sets the Documentum Description (subject).
/// </summary>
/// <value>
/// The Documentum Description.
/// </value>
public string Description
{
get;
set;
}

/// <summary>
/// Gets or sets the keywords.
/// </summary>
/// <value>
/// The keywords.
/// </value>
public string Keywords
{
get;
set;
}

/// <summary>
/// Gets or sets the tags.
/// </summary>
/// <value>
/// The tags.
/// </value>
public string Tags
{
get;
set;
}

/// <summary>
/// Gets or sets the document Contact (doc_contact).
/// </summary>
/// <value>
/// The document Contact.
/// </value>
public string ContactEmail
{
get;
set;
}

/// <summary>
/// Gets or sets a value indicating whether this <see cref="T:EmployeeToolkit.Services.Models.DocumentumRequestCreateModel" /> should be watermarked(doc_watermark).
/// </summary>
/// <value>
/// <c>true</c> if watermarked; otherwise, <c>false</c>.
/// </value>
public bool Watermark
{
get;
set;
}

/// <summary>
/// Gets or sets the rule text(doc_rules).
/// </summary>
/// <value>
/// The rule text.
/// </value>
public string RuleText
{
get;
set;
}

/// <summary>
/// Gets or sets the administration rule text.
/// </summary>
/// <value>
/// The administration rule text.
/// </value>
public string AdministrationRuleText
{
get;
set;
}

/// <summary>
/// Gets or sets the author(authors).
/// </summary>
/// <value>
/// The author.
/// </value>
public string Owner
{
get;
set;
}

/// <summary>
/// Gets or sets the creation date(r_creation_date).
/// </summary>
/// <value>
/// The effective date.
/// </value>
public DateTime CreationDate
{
get;
set;
}

/// <summary>
/// Gets or sets the effective date(a_effective_date).
/// </summary>
/// <value>
/// The effective date.
/// </value>
public DateTime EffectiveDate
{
get;
set;
}

/// <summary>
/// Gets or sets the expiration date(a_expiration_date).
/// </summary>
/// <value>
/// The expiration date.
/// </value>
public DateTime ExpirationDate
{
get;
set;
}

/// <summary>
/// Gets or sets the modified date(r_modify_date).
/// </summary>
/// <value>
/// The modified date.
/// </value>
public DateTime ModifiedDate
{
get;
set;
}

/// <summary>
/// Gets or sets the accessed date(r_access_date).
/// </summary>
/// <value>
/// The accessed date.
/// </value>
public DateTime AccessedDate
{
get;
set;
}

/// <summary>
/// Gets or sets the document file(docFile).
/// </summary>
/// <value>
/// The document file.
/// </value>
public HttpContent DocumentFile
{
get;
set;
}

/// <summary>
/// Gets or sets the content size(fileContent).
/// </summary>
/// <value>
/// The file content.
/// </value>
public Byte[] FileContentInBytes
{
get;
set;
}

/// <summary>
/// Gets or sets the content size(r_content_size).
/// </summary>
/// <value>
/// The content size.
/// </value>
public string FileContectSize
{
get;
set;
}

/// <summary>
/// Gets or sets the content type(a_content_type).
/// </summary>
/// <value>
/// The content type.
/// </value>
public string ContentType
{
get;
set;
}

/// <summary>
/// Gets or sets the doc url(doc_url).
/// </summary>
/// <value>
/// The doc url.
/// </value>
public string Url
{
get;
set;
}
}
}

MVC Controller :

/// <summary>
/// POST: api/v1/documents
/// To protect from overposting attacks, please enable the specific properties you want to bind to, for
/// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
/// </summary>
/// <param name="documentumModel">The documentModel.</param>
/// <returns></returns>
//[Authorize]
[HttpPost]
[Route("", Name = "PostDocumentum")]
[ResponseType(typeof (DocumentumResponseModel))]
//Need to bind as below in order to attach a actual file, currently for testing removed it
//public async Task<string> Create([Bind(Include = "Title,Description,Keywords,ContactEmail,Watermark,RuleText,AdministrationRuleText,EffectiveDate,ExpirationDate,DocumentFile,Url")] DocumentumRequestCreateModel documentumModel)
public async Task<IHttpActionResult> PostDocumentum(DocumentumRequestCreateModel documentumModel)
{
Guard.IsNotNull(documentumModel);

// Commenting for testing purpose

//var user = await this.GetUserFromDatabase();

//To Read the Uploaded File

//if (!this.Request.Content.IsMimeMultipartContent())
// throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

//var provider = new MultipartMemoryStreamProvider();

////var fileName = string.Empty;

//await this.Request.Content.ReadAsMultipartAsync(provider);

//foreach (var file in provider.Contents)
//{
// //fileName = file.Headers.ContentDisposition.FileName.Trim('\"');

// documentumModel.DocumentFile = file;

// documentumModel.ContentType = file.Headers.ContentType.ToString();

// documentumModel.FileContentInBytes = await file.ReadAsByteArrayAsync();
//}

//if (!this.ModelState.IsValid)
//{
// return this.View(documentumModel);
//}

if (documentumModel.RuleText != null)
{
if (RuleTextHelper.IsJson(documentumModel.RuleText))
{
var rulePropertyData = JsonConvert.DeserializeObject<RuleProperty>(documentumModel.RuleText);

var ruleTextHelper = new RuleTextHelper();

var ruleProperty = await ruleTextHelper.Build(rulePropertyData);

documentumModel.RuleText = ruleProperty.RuleText;
}
}

try
{
// ReSharper disable once UnusedVariable
// We are just trying to validate if the Authorize method will successfully validate the rule text
//var validateRuleText = this.authorizationProvider.Authorize(new RuleAuthorizationContext(user), documentumModel.doc_rules);
}
catch
{
//this.ModelState.AddModelError("RuleText", "The provided rules text is not valid.");

//return "The provided rules text is not valid.";
}

//------------Hard Coding User ID for testing purpose--------------->
//documentumModel.AdministrationRuleText = $"(@id == \"{user.EmployeeId}\")";

documentumModel.AdministrationRuleText = $"(@id == \"{"a6000683"}\")";

if (documentumModel.DocumentFile == null && string.IsNullOrEmpty(documentumModel.Url))
{
//return "No file or url added.";
}

if (documentumModel.DocumentFile != null)
{
//switch (documentumModel.DocumentFile.ContentType)
switch (documentumModel.ContentType)
{
case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
break;
case "application/msword":
break;
case "application/vnd.ms-excel":
break;
case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
break;
case "application/vnd.ms-powerpoint":
break;
case "image/tiff":
break;
case "image/jpeg":
break;
case "image/png":
break;
case "image/bmp":
break;
case "application/pdf":
break;
case "text/csv":
break;
case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
break;
default:
return null;
//return "This filetype is not allowed.";
}

//Commenting for testing purpose

//var file = new byte[documentumModel.DocumentFile.InputStream.Length];

//documentumModel.DocumentFile.InputStream.Read(file, 0, file.Length);

//documentumModel.FileContentInBytes = file;
}

try
{
//------------Hard Coding User ID for testing purpose--------------->
documentumModel.Owner = "a6000683";
documentumModel.ExpirationDate = documentumModel.ExpirationDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
documentumModel = await this.documentumRepository.Create(documentumModel);

var document = new Document
{
Pk = Guid.NewGuid(),
Description = documentumModel.Description,
DocumentumIdentifier = documentumModel.DocumentumIdentifier,
Deleted = false,
AdministrationRuleText = documentumModel.AdministrationRuleText,
EffectiveDate = documentumModel.EffectiveDate,
ExpirationDate = documentumModel.ExpirationDate,
Owner = documentumModel.Owner,
RuleText = documentumModel.RuleText,
Title = documentumModel.Title,
Url = documentumModel.Url,
Watermark = documentumModel.Watermark
};

var keywords = documentumModel.Keywords.Split(',').ToList();

foreach (var keyword in keywords)
{
var keywordInDb = this.database.Keywords.SingleOrDefault(k => k.Text == keyword.TrimStart().TrimEnd());

if (keywordInDb != null)
{
keywordInDb.Documents.Add(document);
}
else
{
this.database.Keywords.Add(new Keyword
{
Documents = new List<Document>
{
document
},
Pk = Guid.NewGuid(),
Text = keyword.TrimStart().TrimEnd()
});
}
}

document.ChangeLogs = new List<DocumentChangeLog>
{
new DocumentChangeLog
{
ActionType = ActionType.Created,
Comments = "Initial Creation (No previous values)",
Date = DateTime.Now,
//------------Hard Coding User ID for testing purpose--------------->
Employee = "a6000683"
}
};

document.AccessLogs = new List<DocumentAccessLog>
{
new DocumentAccessLog
{
Pk = Guid.NewGuid(),
Date = DateTime.Now,
Document = document,
//------------Hard Coding User Info for testing purpose--------------->
//Employee = user.EmployeeId,
//JobCode = user.JobCode.ToString(),
//Title = user.JobTitle,
//Location = (user.Location != 0) ? user.Location : 0,
//District = (user.District != 0) ? user.District : 0,
//Market = (user.Market != 0) ? user.Market : 0,
//Territory = (user.Territory != 0) ? user.Territory : 0,
Employee = "a6000683",
JobCode = "11676",
Title = "CW - OTHER",
Location = 900010,
District = 0,
Market = 0,
Territory = 0,
ActionType = ActionType.Created
}
};

this.database.Documents.Add(document);

try
{
await this.database.SaveChangesAsync();
}
catch (DbUpdateException)
{
return null;
}

var response = new DocumentumResponseModel
{
Pk = document.Pk.ToString(),
AdministrationRuleText = document.AdministrationRuleText,
AccessLogs = document.AccessLogs,
ChangeLogs = document.ChangeLogs,
ContactEmail = documentumModel.ContactEmail,
Deleted = document.Deleted,
Description = document.Description,
DocumentumName = documentumModel.DocumentumName,
DocumentumIdentifier = document.DocumentumIdentifier,
CreationDate = documentumModel.CreationDate,
EffectiveDate = document.EffectiveDate,
ExpirationDate = document.ExpirationDate,
Keywords = document.Keywords,
Owner = document.Owner,
RuleText = document.RuleText,
Title = document.Title,
Watermark = document.Watermark,
Url = document.Url
};

return this.CreatedAtRoute("PostDocumentum", new
{
id = response.Pk
}, response);
}
catch (Exception)
{
return null;
//return "Error in Create-DocumentumAPI : " + ex.Message;
}
}

Controller Angular JS:


(function () {

"use strict";

angular.module("akFileUploader", [])

.factory("akFileUploaderService", [
"$q", "$http",
function ($q, $http) {

var getModelAsFormData = function (data) {
console.log(data);
var dataAsFormData = new FormData();
angular.forEach(data, function (value, key) {
console.log(key + " : " + value);
dataAsFormData.append(key, value);
});
console.log(dataAsFormData);
return dataAsFormData;
};

var saveModel = function (data, url) {
var deferred = $q.defer();
$http({
url: url,
method: "POST",
data: getModelAsFormData(data),
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}).success(function (result) {
deferred.resolve(result);
}).error(function (result, status) {
deferred.reject(status);
});
return deferred.promise;
};

return {
saveModel: saveModel
};
}
])
.directive("akFileModel", [
"$parse",
function ($parse) {
return {
restrict: "A",
link: function (scope, element, attrs) {
var model = $parse(attrs.akFileModel);
var modelSetter = model.assign;
element.bind("change", function () {
scope.$apply(function () {
modelSetter(scope, element[0].files[0]);
});
});
}
};
}
]);
})(window, document);


(function () {
"use strict";

angular
.module("app.document-administration", ["akFileUploader"])
.controller("DocumentIndexController", function DocumentIndexController($rootScope, $scope, $http) {

activate();

function activate() {

$scope.init = {
'count': 5,
'page': 1,
'sortBy': 'title',
'sortOrder': 'asc'
};
$scope.filterBy = {
'title': '',
'owner': ''
};

$scope.isExpired = function(expDate) {
var today = new Date();
var expirationDate = new Date(expDate);
if (expirationDate < today) {
return true;
} else {
return false;
}
}

$scope.getDocuments = function(params, paramsObj) {

var urlApi = $rootScope.serviceBaseUrl + "/api/v1/documents?" + params;

return $http.get(urlApi).then(function(response) {

$scope.paginationData = {
"count": response.headers('X-Page-Size'),
"page": response.headers('X-Page-Index'),
"pages": '' + Math.ceil(response.headers('X-Total-Count') / response.headers('X-Page-Size')) + '',
"size": response.headers('X-Total-Count')
};
$scope.headerData = [
{
"key": "Title",
"name": "Title"
},
{
"key": "EffectiveDate",
"name": "Effective Date"
},
{
"key": "ExpirationDate",
"name": "Expiration Date"
},
{
"key": "Owner",
"name": "Owner"
}
];

return {
'rows': response.data,
'header': $scope.headerData,
'pagination': $scope.paginationData,
'sortBy': response.data['sort-by'],
'sortOrder': response.data['sort-order']
}
});
}
}
})
.controller("DocumentsCreateController", function DocumentsCreateController($scope, $http, entityServiceCreate, $window, $modal, $log, $rootScope) {

$scope.$watch("baseUrl", function() {

});
console.log("In Create Controller");
console.log($scope.documentModel);
/* Start RuleBuilder Modal */
$scope.formData = {};

$scope.items = ['item1', 'item2', 'item3'];

$scope.animationsEnabled = true;

var templateUrl = "/Partials/RuleBuilderModal/";

$scope.open = function(size) {

var modalInstance = $modal.open({
animation: $scope.animationsEnabled,
templateUrl: templateUrl,
controller: 'RuleBuilderController',
size: size,
resolve: {
items: function() {
return $scope.items;
}
}
});

modalInstance.result.then(function(selectedItem) {
$scope.showRuleTextBox = false;
}, function() {
//$scope.showRuleTextBox = true;
});
};

$scope.toggleAnimation = function() {
$scope.animationsEnabled = !$scope.animationsEnabled;
};

$rootScope.$watch('ruleBuilderRule', function(newValue) {
$scope.json = newValue;
}, true);

$rootScope.$watch('output', function(newValue) {
$scope.output = newValue;
$scope.documentModel.RuleText = $scope.output;
}, true);

$rootScope.$watch('rawData', function(newValue) {
$scope.rawData = newValue;
}, true);

$rootScope.$watch('ruleModel', function(newValue) {
$scope.ruleModel = newValue;
}, true);

$scope.useRuleBuilder = function() {
$scope.showRuleTextBox = false;
$scope.open('lg');
};
$scope.showRuleTextBox = true;

/* End RuleBuilder */

//$scope.tags = [];

//$scope.options = [];

//$scope.loadTags = function () {

// $http.get(keywordsApi + "?pageSize=9999").then(function (response) {
// $scope.options = response.data.$values;
// });
//};
// console.log(response.data.$values);
// var items = {
// data: [{
// "text": "key1"
// },
// {
// "text": "key2"
// }

// ]

// }
// console.log(items);
// return items.data;
// }
// );

//};

$scope.items = ['upload', 'useURL'];
$scope.selection = $scope.items[0];

$scope.minDate = $scope.minDate ? null : new Date();
$scope.maxDate = new Date(2020, 5, 22);

$scope.format = 'MM/dd/yyyy';

$scope.startDateStatus = {
opened: false
};

$scope.openStartDate = function($event) {
$scope.startDateStatus.opened = true;
};

$scope.endDateStatus = {
opened: false
};

//$scope.urlRequired = false;

$scope.setRequired = function() {
if ($scope.upload == '1') {
$scope.documentModel.Url = "";
} else if ($scope.upload == '2') {
$scope.documentModel.DocumentFile = null;
}
};

$scope.openEndDate = function($event) {
$scope.endDateStatus.opened = true;
};

function formattedDate(date) {
var d = new Date(date || Date.now()),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();

if (month.length < 2) {
month = '0' + month;
}
if (day.length < 2) {
day = '0' + day;
}

return [month, day, year].join('/');
}

$scope.isFileRequired = function() {
if ($scope.selection == '1') {
return true;
} else {
return false;
}
};
$scope.isUrlRequired = function() {
if ($scope.selection == '2') {
return true;
} else {
return false;
}
};
$scope.childMultiSelectOutput = [];

$scope.childMultiSelectSettings = { displayProp: 'Name', idProp: 'Name', externalIdProp: '', enableSearch: true, scrollable: true, scrollableheight: '350px' };

$scope.parentMultiSelectOutput = [];

$scope.parentMultiSelectSettings = { displayProp: 'Name', idProp: 'Name', externalIdProp: '', enableSearch: true, scrollable: true, scrollableheight: '350px' };

$scope.showAddParent = false;

$scope.showAddChild = false;

$scope.submitForm = function() {
if (datesAreValid()) {
if (emailIsValid()) {
$scope.submittingForm();
if ($scope.upload == 2) {
$scope.documentModel.DocumentFile = null;
}
$scope.documentModel.DocumentumName = null;
$scope.documentModel.ExpirationDate = formattedDate($scope.documentModel.ExpirationDate);
$scope.documentModel.EffectiveDate = formattedDate($scope.documentModel.EffectiveDate);

if ($scope.showRuleTextBox != true && $scope.rawData != { "group": { "operator": "||", "rules": [] } }) {
$scope.documentModel.RuleText = JSON.stringify($scope.rawData.group);
} else {
if ($scope.documentModel.RuleText == undefined) {
$scope.documentModel.RuleText = "";
}
}

if ($scope.ruleModel != null) {
$scope.documentModel.RuleProperty = $scope.ruleModel[0];
$scope.documentModel.RuleText = JSON.stringify($scope.ruleModel[0]);
}

var url = $rootScope.serviceBaseUrl + "/api/v1/documents/";

$scope.saveDocument = function (documentModel) {
console.log(documentModel);
entityServiceCreate.saveDocument(documentModel, url)
.then(function(response) {
if (response == 'The provided rules text is not valid.') {
$scope.alerts = [{ type: 'danger', message: 'Rule Text is not valid' }];
} else if (response == "error") {
$scope.alerts = [{ type: 'danger', message: 'An unknown error occurred during document creation' }];
} else if (response == "No file or url added.") {
$scope.alerts = [{ type: 'danger', message: "No file or url provided. Please add one and submit again" }];
} else if (response == "This filetype is not allowed.") {
$scope.alerts = [{ type: 'danger', message: "The type of file that you attempted to upload is not allowed. The allowed types are .xlsx, .xls, .doc, .docx, .ppt, .pptx, .tif, .jpg, .png, .bmp, .pdf and .csv" }];
} else {
$scope.submittedSuccessfully();
$window.location.href = $rootScope.serviceBaseUrl + "/api/v1/documents/" + response;
}

});
};

$scope.saveDocument($scope.documentModel);
} else {
$scope.alerts = [
{ type: 'danger', message: 'The email address you entered is not valid.' }
];
}
} else {
$scope.alerts = [
{ type: 'danger', message: 'The effective date must be before the expiration date.' }
];
}
};

//$scope.alerts = [
// { type: 'info', message: 'Please complete the form then press submit.' }
//];

function datesAreValid() {

var expirationDate = new Date($scope.documentModel.ExpirationDate);
var effectiveDate = new Date($scope.documentModel.EffectiveDate);
if (expirationDate > effectiveDate) {
return true;
} else {
return false;
}
}

function emailIsValid() {
var EMAIL_REGEXP = /^([A-Za-z0-9_\-\.\'])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

if (EMAIL_REGEXP.test($scope.documentModel.ContactEmail)) {
return true;
} else {
return false;
}
}

$scope.validationFailed = function() {
$scope.alerts = [{ type: 'danger', message: 'Oh snap! Change a few things up and try submitting again.' }];
};

$scope.submittingForm = function() {
$scope.alerts = [{ type: 'success', message: 'Form submission in progress, please wait...' }];
};
$scope.submittedSuccessfully = function() {
$scope.alerts = [{ type: 'success', message: 'Form was successfully submitted. You will be redirected to view the details momentarily.' }];
};

$scope.submissionError = function() {
$scope.alerts = [{ type: 'danger', message: 'There was an issue submitting your form, if all values were entered correctly, please contact Help Desk for support.' }];
};

})
.factory("entityServiceCreate",
[
"akFileUploaderService", function (akFileUploaderService) {
var saveDocument = function (documentModel, apiUrl) {
//var url = ($window.location.hostname === "localhost") ? "/ds/documents/create/" : "/documents/create/";
return akFileUploaderService.saveModel(documentModel, apiUrl);
};
return {
saveDocument: saveDocument
};
}
]);
})();


View ContentUpload.cshtml :

<a href="http://www.codeproject.com/Members/model">@model</a> EmployeeToolkit.Services.Models.Documentum.DocumentumRequestCreateModel

@{
Layout = null;
}

<div ng-cloak ng-app="app.document-administration" ng-controller="DocumentsCreateController" ng-init="documentModel.ContactEmail = '@Model.ContactEmail'; baseUrl='@Url.Content("~/")'">
<a ui-sref="app.document-administration">Back to Index</a><!-- Temporary until breadcrumbs works -->

<div class="panel panel-module panel-default" name="content-create-module">
<div class="panel-heading">
<h4>Upload Content</h4>
</div>
<div class="panel-body">
<form name="form" class="content-specs" ng-submit="submitForm()">
<ul class="list-unstyled">
<li class="form-group">
<div class="row">
<div class="col-xs-4">
<label for="documentModel-title">Title</label>
</div>
<div class="col-xs-8">
<div class="form-group">
<input type="text" name="title" class="form-control" id="documentModel-title" placeholder="Enter a title" ng-model="documentModel.Title" ng-required="true">
<span class="help-block"></span>
</div>
</div>
</div>
</li>
<li class="form-group">
<div class="row">
<div class="col-xs-4">
<label for="documentModel-definition">Description</label>
</div>
<div class="col-xs-8">
<div class="form-group">
<textarea type="text" name="description" class="form-control" rows="3" id="documentModel-definition" placeholder="Enter a description" ng-model="documentModel.Description" ng-required="true"></textarea>
<span class="help-block"></span>
</div>
</div>
</div>
</li>
<li class="form-group">
<div class="row">
<div class="col-xs-4">
<label for="documentModel-keywords">Keywords</label>
</div>
<div class="col-xs-8">
<div class="form-group">
<input type="text" name="name" class="form-control" id="documentModel-keywords" placeholder="Enter keywords separated by commas" ng-model="documentModel.Keywords" ng-required="true">
<span class="help-block"></span>
</div>
</div>
</div>
</li>
<li class="form-group">
<div class="row">
<div class="col-xs-4">
<label for="documentModel-timeframe">Timeframe</label>
</div>
<div class="col-xs-8">
<div class="row">
<div class="col-xs-6">
<p class="small date-label">Effective Date</p>
<p class="input-group">
<input type="text" class="form-control" datepicker-popup="{{format}}" ng-model="documentModel.EffectiveDate" is-open="startDateStatus.opened" min-date="minDate" max-date="maxDate" datepicker-options="dateOptions" ng-required="true" close-text="Close"/>
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="openStartDate($event)"><i class="fa fa-calendar"></i></button>
</span>
</p>
</div>
<div class="col-xs-6">
<p class="small date-label">Expiration Date</p>
<p class="input-group">
<input type="text" class="form-control" datepicker-popup="{{format}}" ng-model="documentModel.ExpirationDate" is-open="endDateStatus.opened" min-date="minDate" max-date="maxDate" datepicker-options="dateOptions" ng-required="true" close-text="Close"/>
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="openEndDate($event)"><i class="fa fa-calendar"></i></button>
</span>
</p>
</div>
</div>
</div>
</div>
</li>
<li class="form-group">
<div class="row">
<div class="col-xs-4">
<label for="documentModel-contacts">Contacts</label>
</div>
<div class="col-xs-8">
<input type="email" name="contact" class="form-control" id="documentModel-contacts" placeholder="Enter e-mail address of the content's owner or contact person." ng-model="documentModel.ContactEmail" ng-required="true">
<p class="help-block small">Enter e-mail address of the content's owner or contact person.</p>
</div>
</div>
</li>
@*<li>
<div class="row">
<div class="col-xs-4">
<h5>Groups</h5>
</div>
<div class="col-xs-8">
<ul class="list-unstyled" name="groups-list">
<li>
<p>Not assigned to any groups</p>
</li>
</ul>
</div>
</div>
</li>*@
<li class="form-group">
<div class="row">
<div class="col-xs-4">
<label for="documentModel-rule">Rule</label><small>(Optional)</small>
</div>
<div class="col-xs-8">
<a ng-hide="showRuleTextBox" ng-click="showRuleTextBox = true">Manually Enter Rule Text</a>
<span ng-hide="showRuleTextBox"> | </span><a ng-hide="showRuleTextBox" ng-click="useRuleBuilder()">Modify Rule</a>
<a ng-hide="!showRuleTextBox" ng-click="useRuleBuilder()">Use Rule Builder</a>
<textarea disabled ng-hide="showRuleTextBox" type="text" name="ruletext" class="form-control" placeholder="Enter new rule text" ng-model="documentModel.RuleText"></textarea>
<textarea ng-hide="!showRuleTextBox" type="text" name="ruletext" class="form-control" placeholder="Enter new rule text" ng-model="documentModel.RuleText"></textarea>
<span class="help-block"></span>
</div>
</div>
</li>
<li class="form-group">
<div class="row">
<div class="col-xs-4">
<label for="documentModel-type">Content Type</label>
</div>
<div class="col-xs-8">
@*Value of 1 = File Upload, Value of 2 = Use URL*@
<div class="radio" ng-init="upload=1">
<label class="radio-inline">
<input id="fileUpload" type="radio" name="docTypeRadios" ng-model="upload" value="1" ng-change="setRequired()"> File
</label>
<label class="radio-inline">
<input id="useURL" type="radio" name="docTypeRadios" ng-model="upload" value="2" ng-change="setRequired()"> URL
</label>
</div>

<div class="file-upload" ng-show="upload == '1'">
<input type="file" id="inputFile" data-ak-file-model="documentModel.docFile">
<span class="help-block"></span>
<div class="checkbox">
<input type="checkbox" id="watermark" ng-model="documentModel.Watermark">
<label for="watermark">
Watermark File (PDFs only)
</label>
<span class="help-block"></span>
</div>
</div>
<div ng-show="upload == '2'">
<input type="url" name="contact" class="form-control" id="document-contacts" placeholder="Enter URL" ng-model="documentModel.Url">
</div>
</div>
</div>
</li>
</ul>

<div ng-repeat="alert in alerts" class="alert alert-{{alert.type}}">
{{alert.message}}
</div>

<div class="clearfix">
<button type="submit" class="btn btn-primary pull-right">Create Content</button>
</div>
</form>
</div>
</div>
</div>
AnswerRe: Getting Error as Unsupported Media Content Pin
Atish Dipongkor17-Jan-16 1:21
professionalAtish Dipongkor17-Jan-16 1:21 
GeneralRe: Getting Error as Unsupported Media Content Pin
magesh venkatesan18-Jan-16 5:11
magesh venkatesan18-Jan-16 5:11 
GeneralRe: Getting Error as Unsupported Media Content Pin
Atish Dipongkor18-Jan-16 18:59
professionalAtish Dipongkor18-Jan-16 18:59 
QuestionAnother model data along with this file list Pin
Md._Mehedi_Hasan4-Nov-15 1:45
professionalMd._Mehedi_Hasan4-Nov-15 1:45 
AnswerRe: Another model data along with this file list Pin
Atish Dipongkor4-Nov-15 3:16
professionalAtish Dipongkor4-Nov-15 3:16 
GeneralRe: Another model data along with this file list Pin
Md._Mehedi_Hasan6-Nov-15 2:56
professionalMd._Mehedi_Hasan6-Nov-15 2:56 
QuestionGetting error while upload large file Pin
Member 105711068-Sep-15 23:58
Member 105711068-Sep-15 23:58 
AnswerRe: Getting error while upload large file Pin
Atish Dipongkor9-Sep-15 0:39
professionalAtish Dipongkor9-Sep-15 0:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.