How to download any kind of files with angularJs

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

 

2

Let’s see How to download any kind of files with angularJs

j1.png

 

j2.png

 

Note:-

Just we need to use contentType  in proper format

if (fileName.indexOf(“xls”) > -1 || fileName.indexOf(“xlsx”) > -1) {
var contentType = ‘application/octet-stream’;
} else if (fileName.indexOf(“pdf”) > -1) {
var contentType = ‘application/pdf’;
} else {
var contentType = ‘application/octet-stream’;
}
var fileDownLoadName = fileName;
var def = $q.defer();
$http.post(apiBase + “/portalDocumentDownload”, angular.toJson(helper), { responseType: ‘arraybuffer’ },
{ headers: { ‘Content-Type’: ‘application/json’ } })
.success(function (data, status, headers, config) {
var ieEDGE = navigator.userAgent.match(/Edge/g);
var ie = navigator.userAgent.match(/.NET/g); // IE 11+
var oldIE = navigator.userAgent.match(/MSIE/g);
var blob = new window.Blob([data], {
type: contentType
});
if (ie || oldIE || ieEDGE) {
window.navigator.msSaveBlob(blob, fileDownLoadName);
}
else {
var file = new Blob([data], { type: contentType });
var fileURL = URL.createObjectURL(file);
var a = document.createElement(‘a’);
a.href = fileURL;
a.target = ‘_blank’;
a.download = fileDownLoadName;
document.body.appendChild(a);
a.click();
}
})

Advertisements

read all file names exists in perticular directory

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

 

2

 

Let’s see how to read all file names exists in perticular directory

 

dd1.png

 

string downloadpath = @”C:\\1″;
DirectoryInfo dir = new DirectoryInfo(downloadpath);
var files = dir.GetFiles(“*.*”);
foreach (var file in files)
{
FilesInfo obj = new FilesInfo();
obj.FileName = file.Name;
lstFileinfo.Add(obj);
}

upload file in angular with own directive

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

 

2

 

j1

 

 

Code-

<input type=”text” class=”form-control” ng-model=”filePath” ng-file-select=”onFileSelect($files)” ng-disabled=”isBrowseDisabled”>
<label class=”input-group-btn”>
<span class=”btn btn-primary”>
Browse <input type=”file” style=”display: none;” ng-file-select=”onFileSelect($files)” ng-disabled=”isBrowseDisabled”>
</span>
</label>

 

j2

 

 

Code-

 

app.directive(“ngFileSelect“, function () {
return {
link: function ($scope, el) {
el.bind(“change”, function (e) {
$scope.file = (e.srcElement || e.target).files[0];
var path = e.target.value;
path = path.substring(0, 3);
$scope.filePath = path + $scope.file.name;
//$scope.filePath = e.target.value;
$scope.getFile();
})
}
}
})

 

 

Controller.js

j3

$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;
};

 

j4

 

$scope.getFile = function () {
$scope.progress = 0;
$scope.readAsDataURL($scope.file, $scope)
.then(function (result) {
$scope.xslData = result; // result This is Binary Data
$scope.uploadedDocName = $scope.file.name;
$scope.fileInfodetails = “File name: ” + $scope.filePath + ” ” + $scope.file.size + ” ” + “Bytes”;
//$scope.fileDetails = $scope.filePath;
});
};

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;
}

How to check particular url is exist or not with the help of HttpWebResponse ?

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

 

2

 

Let’s see,

 

How to check particular url is exist or not with the help of HttpWebResponse 

 

[Route(“Check”)]
public HttpResponseMessage Check(string appUrl)
{

//Set as below
appUrl=https://sandippatil.com/Downloads/Training ManualHTML.pdf”;

Uri destURL = new Uri(appUrl);
HttpWebRequest request = HttpWebRequest.CreateHttp(destURL);
request.Method = “HEAD”;
try
{
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
helpEnabled = true;
}
}
catch (Exception ex)
{
helpEnabled = false;
}
HttpResponseMessage resp;
resp = Request.CreateResponse<bool>(HttpStatusCode.OK, helpEnabled);
return resp;
}

 

If doesn’t exists it will throws an exception as shown in below Image.

sk2

 

Another solution is

var appUrl=”https://sandippatil.com/Downloads/Training ManualHTML.pdf”;

bool urlExists;

WebRequest webRequest = WebRequest.Create(appUrl);
WebResponse webResponse;
try
{
webResponse = webRequest.GetResponse();
urlExists= true;
}
catch //If exception thrown then couldn’t get response from address
{
urlExists= false;
}
HttpResponseMessage resp;
resp = Request.CreateResponse<bool>(HttpStatusCode.OK, helpEnabled);
return resp;

 

Working code in WebAPI controller is

 

[Route(“CheckHelpButtonPermission”)]
public HttpResponseMessage CheckHelpButtonPermission(string appUrl)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(appUrl);
webRequest.Method = “GET”;

string responseData = string.Empty;
HttpWebResponse httpResponse = (HttpWebResponse)webRequest.GetResponse();

using (StreamReader responseReader = new StreamReader(httpResponse.GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
helpEnabled = true;
}
}
catch (System.Net.WebException ex)
{
helpEnabled = false;
}

HttpResponseMessage resp;
resp = Request.CreateResponse<bool>(HttpStatusCode.OK, helpEnabled);
return resp;
}