angularjs and spring mvc - upload multiple files in one request - angularjs

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

Related

Force browser to download file from node js response

I am trying to download a file from remote URL using node js and send the file to the browser. After the response returns to my front end code I want to automatically download it. Can someone help? Here is my code snippet:
Backend node js code I am using request to make the remote url call:
var request = require('request');
var config = req.param('config');
res.setHeader("content-disposition", "attachment; filename=" + config.fileName);
request('http://' + config.hostname + ':' + config.port + config.path).pipe(res);
Front end code in angular 1.5x:
var config = {
hostname: APP_CONFIG.API_HOST,
port: APP_CONFIG.API_PORT,
path: '/document,
method: 'GET',
fileName: row.Name,
fileType: row.Type
};
$http.put('/getFileFromUrl', {
config: config
})
.then(function onSuccess(res) {
if (res.data !== null && res.data.error === undefined) {
// .........what should I do here its not auto downloading
if (APP_VARS.isLoader === true) {
APP_VARS.isLoader = false;
grxUI.loading.stop();
}
}
})
This is an example of a Download button that becomes active after the data is loaded from the server:
<a download="data_{{files[0].name}}" xd-href="data">
<button ng-disabled="!data">Download</button>
</a>
The xdHref Directive
app.module("myApp").directive("xdHref", function() {
return function linkFn (scope, elem, attrs) {
scope.$watch(attrs.xdHref, function(newVal) {
if (newVal) {
elem.attr("href", newVal);
}
});
};
});
The DEMO on PLNKR.
Downloading Binary Files with AngularJS
When downloading binary files it is important to set the responseType attribute of the XHR.
var config = { responseType: 'blob' }
var httpPromise = $http.get(url, config);
httpPromise.then(function (response) {
$scope.data = response.data;
});
For more information, see MDN XHR API - ResponseType.

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

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.

Download file with Angular and Django

I have a table containing a list of files fetched from the server. I also have a button, that downloads the selected file. So I made a function which call a service and it opens the response (the file) in a new window, so the user can download it.
Controller:
$scope.download = function() {
if ($scope.cancelPromise) {
$scope.cancelPromise.resolve();
}
$scope.cancelPromise = $q.defer();
UserFileSrv.downloadFile.download(
{
fileId: $scope.selectedFile.id
},function(data) {
if (data) {
toaster.pop('success', 'Success', 'success');
window.open(data);
}
}, function(error) {
if (error) {
toaster.pop('error', 'Error', error);
}
}
);
};
The service:
angular.module('app').factory('UserFileSrv', ['$resource', function($resource) {
var userFile = {
downloadFile: $resource('my_url/:fileId/?', {
fileId: '#fileId'
}, {
download: {
method: 'GET',
isArray: false
}
})
};
return userFile;
}]);
The browser shows the 'success' toaster, but it opens a window which contains this string: Cannot GET /%5Bobject%20Object%5D
Note: the Content-Type of the response is: application/json
It seems that you try to pass the downloaded content to the window.open function.
window.open accept the url as the first argument.
You can solve your problem in two cases:
1) Form the url to the resource (ex: 'my_url/12343') and pass it to the window open. But make sure that your server returns your response with header Content-Disposition=attachment;fileName=someFileName. It will force the browser to process the response as an attachment.
2)Otherwise you can use Blob. (it won't work in IE 9 or less)
https://developer.mozilla.org/en-US/docs/Web/API/Blob
Instead of windows.open you can make the following:
function downloadBlob(fileName, blob){
//IE case
if (!!window.navigator.msSaveBlob){
window.navigator.msSaveBlob(blob, fileName);
return;
}
//create url
var url = URL.createObjectURL(blob);
//create invisible acnhor, to specify the file name
var a = document.createElement('a');
document.body.appendChild(a);
a.style = "display: none";
a.href = url;
a.download = fileName;
a.click();
setTimeout(function(){
URL.revokeObjectURL(url);
document.body.removeChild(a);
}, 100);
}
var data = {x: 1, y:2, name: 'abc'};
var blob = new Blob([JSON.stringify(data)], {type : 'octet/stream'});
downloadBlob('myData.json', blob)
The full solution which shows how to download blobs with ngResource is here

File upload in Grails application using angular js

I'm working on a Grails (2.3.7) application with AngularJS. I've to upload files in my application. Since the front end is managed by Angular , I'm uploading my file from Angular controller. I've gone through This
and this discussions , and tried to upload as follows.
My file uploader is
<input type="file" ng-file-select="onFileSelect($files)">
Angular controller is
myapp.controller('createWebController',['$scope','$http','$upload',function($scope,$http,$upload){
$scope.onFileSelect = function($files) {
var file = $files[0];
console.log(file)
$upload.upload({
url: 'UploadLogo/upload', //upload.php script, node.js route, or servlet url
file: file,
method: 'POST' ,
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(function(data){ console.log(data)})
;
};
}])
on the server , I'm using this service and the upload handler code is
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.MultipartFile
import org.codehaus.groovy.grails.web.context.ServletContextHolder
class UploadLogoController {
FileUploadService fileUploadService
def upload() {
def avatarImage = request.getFile('file')
if (!avatarImage.isEmpty())
{
userInstance.avatar = fileUploadService.uploadFile(avatarImage, "logo.png", "~/Desktop/upload")
render "ok"
}
else
{
render "Empty"
}
}
}
But the problem is I'm getting a 500 (Internal Server Error) from grails. The file is not being uploaded.
also getting response as Cannot invoke method isEmpty() on null object
Which means the file has not been sent to the server. Whats the problem here.. Please help..
Try this way. You could create a custom directive for the file upload control
myapp.directive('ngFileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.ngFileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};}])
and in your html use <input type="file" ng-file-model="myFile" />
Then you could create a custom service to do the file upload. Note that its not necessary to create service but it can easily reuse in later file uploads just by injecting the service.
myapp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl,filename){
var fd = new FormData();
fd.append('file', file);
fd.append('filename', filename);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(data){
console.log(data)
})
.error(function(data){ console.log(data)
});
};}]);
The uploadFileToUrl takes 3 arguments , the file itself , the URL to upload and the file name to be saved as.(You can customize this as you wish) . Use the $http.post to post data.
Finally in your controller , include this
var file = $scope.myFile;
var filename = 'YourFileName'
var uploadUrl = '/UploadLogo/upload' // don't forget to include the leading /
fileUpload.uploadFileToUrl(file, uploadUrl,filename);

How to Display blob (.pdf) in an AngularJS app

I have been trying to display pdf file which I am getting as a blob from a $http.post response. The pdf must be displayed within the app using <embed src> for example.
I came across a couple of stack posts but somehow my example doesn't seem to work.
JS:
According to this doc, I went on and tried...
$http.post('/postUrlHere',{myParams}).success(function (response) {
var file = new Blob([response], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.content = fileURL;
});
Now from what I understand, fileURL creates a temporary URL that the blog can use as a reference.
HTML:
<embed src="{{content}}" width="200" height="200"></embed>
I am not sure how to handle this in Angular, the ideal situation would be to (1) assign it to a scope, (2) 'prepare/rebuild' the blob to a pdf (3) pass it to the HTML using <embed> because I want to display it within the app.
I have been researching for more than a day now but somehow I can't seem to understand how this works in Angular... And let's just assume the pdf viewer libraries out there weren't an option.
First of all you need to set the responseType to arraybuffer. This is required if you want to create a blob of your data. See Sending_and_Receiving_Binary_Data. So your code will look like this:
$http.post('/postUrlHere',{myParams}, {responseType:'arraybuffer'})
.success(function (response) {
var file = new Blob([response], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
});
The next part is, you need to use the $sce service to make angular trust your url. This can be done in this way:
$scope.content = $sce.trustAsResourceUrl(fileURL);
Do not forget to inject the $sce service.
If this is all done you can now embed your pdf:
<embed ng-src="{{content}}" style="width:200px;height:200px;"></embed>
I use AngularJS v1.3.4
HTML:
<button ng-click="downloadPdf()" class="btn btn-primary">download PDF</button>
JS controller:
'use strict';
angular.module('xxxxxxxxApp')
.controller('xxxxController', function ($scope, xxxxServicePDF) {
$scope.downloadPdf = function () {
var fileName = "test.pdf";
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
xxxxServicePDF.downloadPdf().then(function (result) {
var file = new Blob([result.data], {type: 'application/pdf'});
var fileURL = window.URL.createObjectURL(file);
a.href = fileURL;
a.download = fileName;
a.click();
});
};
});
JS services:
angular.module('xxxxxxxxApp')
.factory('xxxxServicePDF', function ($http) {
return {
downloadPdf: function () {
return $http.get('api/downloadPDF', { responseType: 'arraybuffer' }).then(function (response) {
return response;
});
}
};
});
Java REST Web Services - Spring MVC:
#RequestMapping(value = "/downloadPDF", method = RequestMethod.GET, produces = "application/pdf")
public ResponseEntity<byte[]> getPDF() {
FileInputStream fileStream;
try {
fileStream = new FileInputStream(new File("C:\\xxxxx\\xxxxxx\\test.pdf"));
byte[] contents = IOUtils.toByteArray(fileStream);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String filename = "test.pdf";
headers.setContentDispositionFormData(filename, filename);
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
return response;
} catch (FileNotFoundException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
return null;
}
michael's suggestions works like a charm for me :)
If you replace $http.post with $http.get, remember that the .get method accepts 2 parameters instead of 3... this is where is wasted my time... ;)
controller:
$http.get('/getdoc/' + $stateParams.id,
{responseType:'arraybuffer'})
.success(function (response) {
var file = new Blob([(response)], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.content = $sce.trustAsResourceUrl(fileURL);
});
view:
<object ng-show="content" data="{{content}}" type="application/pdf" style="width: 100%; height: 400px;"></object>
I faced difficulties using "window.URL" with Opera Browser as it would result to "undefined". Also, with window.URL, the PDF document never opened in Internet Explorer and Microsoft Edge (it would remain waiting forever). I came up with the following solution that works in IE, Edge, Firefox, Chrome and Opera (have not tested with Safari):
$http.post(postUrl, data, {responseType: 'arraybuffer'})
.success(success).error(failed);
function success(data) {
openPDF(data.data, "myPDFdoc.pdf");
};
function failed(error) {...};
function openPDF(resData, fileName) {
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([resData], { type: 'application/pdf' });
if (ie || oldIE || ieEDGE) {
window.navigator.msSaveBlob(blob, fileName);
}
else {
var reader = new window.FileReader();
reader.onloadend = function () {
window.location.href = reader.result;
};
reader.readAsDataURL(blob);
}
}
Let me know if it helped! :)
Adding responseType to the request that is made from angular is indeed the solution, but for me it didn't work until I've set responseType to blob, not to arrayBuffer. The code is self explanatory:
$http({
method : 'GET',
url : 'api/paperAttachments/download/' + id,
responseType: "blob"
}).then(function successCallback(response) {
console.log(response);
var blob = new Blob([response.data]);
FileSaver.saveAs(blob, getFileNameFromHttpResponse(response));
}, function errorCallback(response) {
});
Most recent answer (for Angular 8+):
this.http.post("your-url",params,{responseType:'arraybuffer' as 'json'}).subscribe(
(res) => {
this.showpdf(res);
}
)};
public Content:SafeResourceUrl;
showpdf(response:ArrayBuffer) {
var file = new Blob([response], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
this.Content = this.sanitizer.bypassSecurityTrustResourceUrl(fileURL);
}
HTML :
<embed [src]="Content" style="width:200px;height:200px;" type="application/pdf" />
I have struggled for the past couple of days trying to download pdfs and images,all I was able to download was simple text files.
Most of the questions have the same components, but it took a while to figure out the right order to make it work.
Thank you #Nikolay Melnikov, your comment/reply to this question was what made it work.
In a nutshell, here is my AngularJS Service backend call:
getDownloadUrl(fileID){
//
//Get the download url of the file
let fullPath = this.paths.downloadServerURL + fileId;
//
// return the file as arraybuffer
return this.$http.get(fullPath, {
headers: {
'Authorization': 'Bearer ' + this.sessionService.getToken()
},
responseType: 'arraybuffer'
});
}
From my controller:
downloadFile(){
myService.getDownloadUrl(idOfTheFile).then( (response) => {
//Create a new blob object
let myBlobObject=new Blob([response.data],{ type:'application/pdf'});
//Ideally the mime type can change based on the file extension
//let myBlobObject=new Blob([response.data],{ type: mimeType});
var url = window.URL || window.webkitURL
var fileURL = url.createObjectURL(myBlobObject);
var downloadLink = angular.element('<a></a>');
downloadLink.attr('href',fileURL);
downloadLink.attr('download',this.myFilesObj[documentId].name);
downloadLink.attr('target','_self');
downloadLink[0].click();//call click function
url.revokeObjectURL(fileURL);//revoke the object from URL
});
}
A suggestion of code that I just used in my project using AngularJS v1.7.2
$http.get('LabelsPDF?ids=' + ids, { responseType: 'arraybuffer' })
.then(function (response) {
var file = new Blob([response.data], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
$scope.ContentPDF = $sce.trustAsResourceUrl(fileURL);
});
<embed ng-src="{{ContentPDF}}" type="application/pdf" class="col-xs-12" style="height:100px; text-align:center;" />

Resources