using ng-file-upload to upload file to hard drive - angularjs

I want to use ng-file-upload to upload files to hard drive in the server
this.uploadFiles = function(files, errFiles) {
this.files = files;
this.errFiles = errFiles;
angular.forEach(files, function(file) {
file.upload = Upload.upload({
url: 'C:\Java\logs',
data: {file: file}
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
this.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
file.progress = Math.min(100, parseInt(100.0 *
evt.loaded / evt.total));
});
});
}
when I use this code I get this error
angular.js:10765 XMLHttpRequest cannot load file:///C:/Javalogs. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
that what I did but it didn't work
this.uploadFiles = function(file, errFiles) {
Upload.dataUrl(file[0], true).then(function (base64Url) {
var filename = 'test.jpg';
var a = document.createElement("a");
var myDocument = getFileContainer(base64Url);
var blob = new Blob([myDocument.data], {type: 'image/jpg'});
var file = new File([blob], 'imageFileName.jpg');
if(window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
}
else{
var elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(file);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}
})
the picture is generated but I can't view it

I send them via a base64 url to the backend. It depends on which data you need but it should roughly look like the following code.
function getMimeTypeFromUrl(imageUrl) {
return imageUrl.substring(imageUrl.indexOf(':') + 1, imageUrl.indexOf(';'));
}
function getDataFromUrl(imageUrl){
return imageUrl.substring(imageUrl.indexOf(',') + 1);
}
function getFileContainer(imageUrl, file){
return {
data:getDataFromUrl(imageUrl),
mimeType: getMimeTypeFromUrl(imageUrl),
filename: file.name,
}
}
this.uploadFiles = function(files, errFiles) {
Upload.dataUrl(file, true).then(function (base64Url) {
myDocument = getFileContainer(base64Url, file);
//here you have to post myDocument
}
}
Upload is a service of ng-file-upload, which loads the file to the browser as a base64 url.
I hope I could help you.

Related

downloading text file in postman but not in browser using restapi in angularjs

$scope.newFile is my response from backend. Actually my response should be a text file, which is working in postman.But in browser , I am getting
Cannot GET
/Organizer/%7B%22data%22:%22id/tname/temail/tphone/twebsite/tvenue/ttags/n83/tAny%20Name/ta#b.com/t9009009009/thttp://www.anyname.com/tHall%20A/ttag1,%20tag2,%20tag3/nsunitha/tsunitha#gmail.com/t55555541/thttp://www.sunitha.com/nSuhasini/tsuha#gmail.com/t955555544/thttp://www.suha.com/nRaichel/traichel#gmail.com/t955548458/thttp://www.raichel.com/n%22,%22status%22:200,%22config%22:%7B%22method%22:%22GET%22,%22transformRequest%22:[null],%22transformResponse%22:[null],%22jsonpCallbackParam%22:%22callback%22,%22headers%22:%7B%22Authorization%22:%22Token%2013946cc6c575d61b042b01b6905f1d239b3d9b08%22,%22Accept%22:%22application/json,%20text/plain,%20*/*%22%7D,%22url%22:%22http://http://localhost/1290//entity/campaigns/download_exhibitors/%22%7D,%22statusText%22:%22OK%22,%22xhrStatus%22:%22complete%22%7D
Service.js
var url =' http://localhost/1290/';
function downloadExhibitor() {
var token = 129821sahh;
var auth = "Token" + ' ' + token;
var config = {
headers: {
'Content-Type': 'text/plain',
'Authorization': auth
}
}
return $http.get(url + 'entity/campaigns/download_exhibitors/', config)
.then(successHandler, errorHandler);
}
function successHandler(response){
/* we've got file's data from server */
return response.data;
}
function errorHandler(error){
/* we've got error response from server */
throw new Error('ERROR ' + error);
}
and eventually the service invocation
JS:
$scope.newFile = "";
service.downloadExhibitor()
.then(function(data){
$scope.newFile = data;
}, function(error){
console.log(error);
});
HTML:
<button class="btn" ng-click="downloadAllExhibitors();">
<a ng-href="{{newFile}}" target="_blank">Download</a></button>
You can try below code in controller...
var file = new Blob([data], {
type : 'text/plain'
});
if (navigator.userAgent.indexOf('MSIE') !== -1
|| navigator.appVersion.indexOf('Trident/') > 0) {
window.navigator.msSaveOrOpenBlob(file);
} else {
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
Following code in controller made my work simple , and it downloaded the file finally.
var file = new Blob([data], {
type: 'text/plain'
});
if (navigator.userAgent.indexOf('MSIE') !== -1 ||
navigator.appVersion.indexOf('Trident/') > 0) {
window.navigator.msSaveOrOpenBlob(file);
} else {
var a = window.document.createElement("a");
a.href = window.URL.createObjectURL(file, {
type: "text/plain"
});
a.download = "filename.csv";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}

Download PDF using Angular

I'm trying to download PDF from a WebApi using Angular but the file is only 15 bytes. If I log the data being received from the WebApi it's an arraybuffer with the expected size
The WebApi
[HttpGet]
public HttpResponseMessage MatchRegistrationReport(int matchId)
{
try
{
var gen = new MSReports.Components.MatchRegistration();
byte[] bytes = gen.GeneratePDF(matchId, 10);
var stream = new MemoryStream(bytes);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(stream)
//Content = new ByteArrayContent(bytes)
};
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = gen.ReportName + ".pdf"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return result;
}
catch (Exception ex)
{
Log.Error(ex.Message);
return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
}
}
The Angular controller
$scope.Print = function () {
$scope.message = "Downloading";
reportResource.printMatchRegistration($scope.match.Id).then(function (data, status, headers, config) {
var file = new Blob([data], {
type: 'application/csv'
});
//trick to download store a file having its URL
var fileURL = URL.createObjectURL(file);
var a = document.createElement('a');
a.href = fileURL;
a.target = '_blank';
a.download = 'MatchRegistration.pdf';
document.body.appendChild(a);
a.click();
//$scope.message = "Completed";
}, function (data, status, headers, config) {
$scope.message = "A error occurred";
});
}
and the resource
printMatchRegistration: function (matchId) {
return $http({
method: 'get',
url: this.getApiPath() + "MatchRegistrationReport?matchId=" + matchId,
headers: {
'Content-type': 'application/pdf',
},
responseType: 'arraybuffer'
});
I believe it has something to do with the content-type but can' figure out what.
Hi just found the answer
Change to this
reportResource.printMatchRegistration($scope.match.Id).then(function (response) {
var file = new Blob([response.data], {
type: 'application/pdf'
});
and this
printMatchRegistration: function (matchId) {
var data = { 'matchId': matchId };
return $http({
method: 'get',
url: this.getApiPath() + "MatchRegistrationReport",
params: data,
headers: {
'Content-type': 'application/pdf',
},
responseType: 'arraybuffer'
});
},

IE10 - Page Blank when window.open(trustedURL) - PDF ANGULAR JS

I tried to generate a PDF since data returned from API.
All working find exept for IE 10, Edge which open a blank window ! I dont know what happening...
Controller function :
(fileRequest = User.getFile($rootScope.PARAMS, 'facture', 'arraybuffer')).then(function(dataFactureFile)
{
var file = new Blob([dataFactureFile], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.content = $sce.trustAsResourceUrl(fileURL);
$timeout(function()
{
if(action == 'view')
{
$window.open($scope.content);
}
if(action == 'download')
{
var anchor = document.createElement("a");
anchor.setAttribute('download', false);
anchor.download = 'FACTURE-' + $scope.infosFacture.type + '-' + $scope.infosFacture.date + '.pdf';
anchor.href = $scope.content;
anchor.click();
}
}, 500);
}, function(reason){
if(reason != 'aborted')
{
// REJECT
$scope.popin(reason.errorCode, reason.errorMsg);
}
});
Service :
getFile: function(user, type, type_response)
{
var deferredAbort = $q.defer();
var request = $http({
method: "post",
url: $rootScope.directory + 'api/' + type,
data: user,
headers: {
'Content-Type': 'api/downloadPDF'
},
responseType : type_response,
timeout: deferredAbort.promise
}).then(
function(response) {
return(response.data);
},
function(response) {
return($q.reject('aborted'));
}
);
request.abort = function() {
deferredAbort.resolve();
};
return(request);
},
In addition, the "anchor.click()" seems to not working with IE :/, somebody have a tip for simulate download click ?
Thank's you

Upload photo and video together with angularjs

I need to upload photos and videos together.
I am using the ng-file-upload
my mvc controller :
[HttpPost]
public ContentResult Add(List<HttpPostedFileBase> file, VideoViewModel item)
{
return Content(_output.ConvertToJson(), "application/json");
}
my javascript codes :
$scope.item = {
Address: '',
Name: ''
};
$scope.files = [];
$scope.file = null;
$scope.video = null;
$scope.response = {};
$scope.confirmAdd = function () {
if ($scope.add_form.$valid) {
$scope.files[0] = $scope.file;
$scope.files[1] = $scope.video;
$upload.upload({
url: 'User/Add',
method: 'POST',
data: $scope.item,
file: $scope.files,
}) .progress(function (evt) {
$scope.percent = parseInt(100.0 * evt.loaded / evt.total);
}).success(function (data, status, headers, config) {
$scope.response = data;
}).error(function (err) {
$scope.percent = 0;
});
} else {
$scope.add_form.submitted = true;
}
}
$scope.onFileSelect = function ($files) {
$scope.file = $files[0];
};
$scope.onVideoSelect = function ($files) {
$scope.video = $files[0];
};
error :
IIS 8.0 Detailed Error - 404.13 - Not Found
The request filtering module is configured to deny a request that exceeds the request content length
Most likely causes:
Request filtering is configured on the Web server to deny the request because the content length exceeds the configured value
How do I solve the problem?

angularjs and spring mvc - upload multiple files in one request

I want to implement file uploading in my web application, I am using angular.js on client side and spring mvc on server side.
I managed to get single file upload and multiple file upload working by using https://github.com/danialfarid/angular-file-upload. The thing is, when I upload multiple files each one of them is coming to me as separate request (which is obvious event after reading example code):
//inject angular file upload directives and service.
angular.module('myApp', ['angularFileUpload']);
var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
$scope.onFileSelect = function($files) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var $file = $files[i];
$scope.upload = $upload.upload({
url: 'server/upload/url', //upload.php script, node.js route, or servlet url
// method: POST or PUT,
// headers: {'headerKey': 'headerValue'}, withCredential: true,
data: {myObj: $scope.myModelObj},
file: $file,
//(optional) set 'Content-Desposition' formData name for file
//fileFormDataName: myFile,
progress: function(evt) {
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}
}).success(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
})
//.error(...).then(...);
}
}
}];
there is an iteration through all the files.
Now I am wondering if it is possible to somehow upload multiple files as one, single request.
on spring controller side create
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String save(#ModelAttribute("filesForm") FileUploadForm filesForm) {
List<MultipartFile> files = filesForm.getFiles();
//do something
}
public class FileUploadForm
{
private List<MultipartFile> files;
// geters and setters ...
}
on client side upload service
return {
send: function(files) {
var data = new FormData(),
xhr = new XMLHttpRequest();
xhr.onloadstart = function() {
console.log('Factory: upload started: ', file.name);
$rootScope.$emit('upload:loadstart', xhr);
};
xhr.onerror = function(e) {
$rootScope.$emit('upload:error', e);
};
xhr.onreadystatechange = function(e)
{
if (xhr.readyState === 4 && xhr.status === 201)
{
$rootScope.$emit('upload:succes',e, xhr, file.name ,file.type);
}
};
angular.forEach(files, function(f) {
data.append('files', f, f.name);
});
xhr.open('POST', '../upload');
xhr.send(data);
}
};

Resources