Upload Multiple files in angular js with collecting binary data of each of them

R(In order to Enlarge images Please Right Click and Open images in New Tab).

 

2

 

Let’s see how to collect binary data of each file which is uploaded through input type files

 

HTML CODE:

1.png
<input type=”file” name=”files” id=”files” multiple onchange=”angular.element(this).scope().getDocs(this)”>

<button id=”btnSubmit” data-ng-click=”vm.saveDocs()”>Submit</button>

 

controller.js code=>

 

2.png

 

 Code-

$scope.getDocs = function () {
vm.data = ‘none’;
var len = document.getElementById(‘files’).files.length;
for (var i = 0; i < len; i++) {
var filesInfo = document.getElementById(‘files’).files[i],
r = new FileReader();
var fileName = filesInfo.name;
var fileSize = filesInfo.size;
var fileType = filesInfo.type;
var re = /(?:\.([^.]+))?$/;
var fileExtension = re.exec(filesInfo.name)[1];

if (vm.filesUploadInfo.length == 0) {
vm.filesUploadInfo.push({
FileId: i,
FileName: fileName,
FileSize: fileSize,
FileType: fileType,
FileExtension: fileExtension
});
}
else {
var existingFiles = Enumerable.From(vm.filesUploadInfo).Where(function (x) { return x.FileName == fileName }).ToArray();
if (existingFiles.length == 0) {
vm.filesUploadInfo.push({
FileId: vm.filesUploadInfo.length,
FileName: fileName,
FileSize: fileSize,
FileType: fileType,
FileExtension: fileExtension
});
}
}
}
vm.filesData = “”;
getColumnsUploadedDocs();
vm.portalUploadDocsData.data(vm.filesUploadInfo);
}

 

aq1

 

 

Code-

//QQ1
var binaryData = null;
$scope.onLoad = function (reader, deferred, scope) {
return function () {
scope.$apply(function () {
deferred.resolve(reader.result);
});
};
};
$scope.onError = function (reader, deferred, scope) {
return function () {
scope.$apply(function () {
deferred.reject(reader.result);
});
};
};
$scope.onProgress = function (reader, scope) {
return function (event) {
scope.$broadcast(“fileProgress”,
{
total: event.total,
loaded: event.loaded
});
};
};
$scope.getReader = function (deferred, scope) {
var reader = new FileReader();
reader.onload = $scope.onLoad(reader, deferred, scope);
reader.onerror = $scope.onError(reader, deferred, scope);
reader.onprogress = $scope.onProgress(reader, scope);
return reader;
};
$scope.readAsDataURL = function (file, scope) {
var deferred = $q.defer();
var reader = $scope.getReader(deferred, scope);
reader.readAsDataURL(file);
return deferred.promise;
};
//QQ2

 

aq2

 

Code-

vm.i = 0;
var k = parseInt(vm.i);

$scope.getFile = function (fileInfoDetails) {
$scope.progress = 0;
$scope.readAsDataURL(fileInfoDetails, $scope)
.then(function (result) {
binaryData = result;
createFilesBinaryDataInfo(fileInfoDetails,binaryData);
});
};

function saveDocs() {
if (isValidData()) {
vm.i = 0;
vm.data = ‘none’;
vm.filesInfo = [];
var len = document.getElementById(‘files’).files.length;
for (var i = 0; i < len; i++) {
var filesInfo = document.getElementById(‘files’).files[i];
$scope.getFile(filesInfo);
}
}
}

 

aq3

 

CODE-

 

function createFilesBinaryDataInfo(filesInfo, binaryData)
{
k = parseInt(vm.i);
var fileName = filesInfo.name;
var fileType = filesInfo.type;
var fileSize = filesInfo.size;
var re = /(?:\.([^.]+))?$/;
var fileExtension = re.exec(filesInfo.name)[1];
var binaryFileInfo = binaryData;
var existingFiles = Enumerable.From(vm.filesInfo).Where(function (x) { return x.FileName == fileName }).ToArray();
if (existingFiles.length == 0) {
var tmpParam = {
FileName: fileName,
FileType: fileType,
FileSize: fileSize,
FileExtension: fileExtension,
FileBinaryData: binaryFileInfo
};
vm.filesInfo.push(tmpParam);
}
k++;
vm.i = k;
senduploadedDOcs();
}

 

Let’s see how to send it to the WebAPI Controller through [FromBody]

 

//controller.js

bt4

Code-

 

function senduploadedDOcs()
{
if (document.getElementById(‘files’).files.length == vm.filesInfo.length) {
vm.selectedDocTypeId = angular.element(“#drpUploadType option:selected”).val();
vm.SelectedDocTypeName = angular.element(“#drpUploadType option:selected”).text();
vm.SelectedDocTypeName = vm.SelectedDocTypeName.trim();
vm.claimPatientFirstName = vm.claimPatientFirstName.trim();
vm.claimPatientLastName = vm.claimPatientLastName.trim();
vm.claimMemberId = vm.claimMemberId.trim();
vm.claimNumber = vm.claimNumber.trim();

if (vm.claimDOSFrom.length > 0 && isNaN(Date.parse(vm.claimDOSFrom)))
vm.claimDOSFrom = “”;

var currentFselectedFiles = vm.filesInfo;

if (vm.claimPatientFirstName.length > 0 ||
vm.claimPatientLastName.length > 0 ||
vm.claimMemberId.length > 0 ||
vm.claimNumber.length > 0 ||
vm.claimDOSFrom ||
vm.selectedDocTypeId ||
vm.filesInfo)
dataservice.uploadPortaldocs(vm.selectedDocTypeId, vm.SelectedDocTypeName,vm.claimPatientFirstName, vm.claimPatientLastName, vm.claimMemberId, vm.claimNumber,
vm.claimDOSFrom, vm.filesInfo).then(function (response) {
if (response.length > 0) {

} else {

}
}, function () {
logger.error(‘Failed Getting Claim Search Results’, ”, ‘Member API’);
});
}
}

 

 

 

service.js

 

var IdentityDTO = {
UserId: $rootScope.userProfile.userId,
SelectedOrganizationId: $rootScope.userProfile.selectedRCMOrg.organizationIdField,
SelectedCrmClientId: $rootScope.userProfile.selectedRCMOrg.crmClientIdField,
UserName: $rootScope.userProfile.firstName + ‘ ‘ + $rootScope.userProfile.lastName
};

var helper = {
user: IdentityDTO,
param: ClaimPortalDocsDTO,
filesInfo: filesInfo,
}

var def = $q.defer();
$http.post(apiBase + “/portalDocumentUpload“, angular.toJson(helper),
{ headers: { ‘Content-Type’: ‘application/json’ } })
.success(function (data, status, headers, config) {

}

bt2

 

APIController.cs

 

public class PortalDocumentUploadController : ApiController
{
public class ClaimPortalDocsDTO
{
public int SelectedDocTypeId { get; set; }
public string SelectedDocTypeName { get; set; }
public string PatientFirstName { get; set; }
public string PatientLastName { get; set; }
public string MemberId { get; set; }
public string ClaimNumber { get; set; }
public DateTime? DOSFrom { get; set; }
public Guid ClientId { get; set; }
}
public class FilesInfo
{
public string FileName { get; set; }
public string FileType { get; set; }
public int FileSize { get; set; }
public string FileExtension { get; set; }
// public byte[] FileBinaryData { get; set; } //Won’t works
public string FileBinaryData { get; set; }
}
public class ClaimPortalDocsHelper
{
public UserIdentity user { get; set; }
public ClaimPortalDocsDTO param { get; set; }
public List<FilesInfo> filesInfo { get; set; }
}
public class UserIdentity
{
public int UserId { get; set; }
public int SelectedOrganizationId { get; set; }
public Guid SelectedCrmClientId { get; set; }
}
// Handle CORS options pre-flight check
[AllowAnonymous]
public HttpResponseMessage Options()
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}

[Authorize]
public HttpResponseMessage Post([FromBody]ClaimPortalDocsHelper helper)
{
HttpResponseMessage resp;
resp = Request.CreateResponse(HttpStatusCode.OK);
return resp;
}

}

 

bt3

 

Let’s see in Debug mode ,How data comes to WebAPI Controller

bt5

 

aq4

 

Now in controller.cs do below changes to get exact binary Data

h1

[Authorize]
public HttpResponseMessage Post([FromBody]ClaimPortalDocsHelper helper)
{
HttpResponseMessage resp;
resp = Request.CreateResponse(HttpStatusCode.OK);
List<FilesInfo> filesInfo = helper.filesInfo;
for (var i = 0; i < filesInfo.Count;i++ )
{
string fileType = filesInfo[i].FileType;
string fContent = filesInfo[i].FileBinaryData;
fContent = fContent.Replace(fileType, String.Empty);
fContent = fContent.Replace(“data:;base64,”, String.Empty);
filesInfo[i].FileBinaryData = fContent;
}

resp = Request.CreateResponse(HttpStatusCode.OK);
return resp;
}

 

h2.png

 

 

h3

 

Now let’s see how to write this code to Local Drive or Path:

hg1.png

 

CODE

[Authorize]
public HttpResponseMessage Post([FromBody]ClaimPortalDocsHelper helper)
{
HttpResponseMessage resp;
resp = Request.CreateResponse(HttpStatusCode.OK);
List<FilesInfo> filesInfo = helper.filesInfo;
for (var i = 0; i < filesInfo.Count;i++ )
{
string fileType = filesInfo[i].FileType;
string fContent = filesInfo[i].FileBinaryData;
fContent = fContent.Replace(fileType, String.Empty);
fContent = fContent.Replace(“data:;base64,”, String.Empty);
byte[] fileData = Convert.FromBase64String(fContent);
//Code indicates how to write files on local drive
string filePath = @”C:\\1\\” + filesInfo[i].FileName;
Stream stream = new MemoryStream(fileData);
using (Stream file = File.Create(filePath))
{
stream.CopyTo(file);
}

//Stream stream = new MemoryStream(fileData);
//using (Stream file = File.Create(filePath))
//{
//stream.CopyTo(file);
//}

//for above line

//OR

//You can use

File.WriteAllBytes(filePath , fileData);
}

resp = Request.CreateResponse(HttpStatusCode.OK);
return resp;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s