I don't have much front-end experience, so please bear with me.
I have a local Angular app in browser (no back-end) and I want to upload a JSON file so that I can show the uploaded data on graphs. Since I don't know if I can just fs.readFile from Angular, I've chosen ng-file-upload to load the file in a nice way (from the file browser). Let me know if it isn't the right tool, though...
So I've copied the code from the official JS Fiddle on the repo. Had to modify it a bit to allow me upload anything -- remove validations.
var app = angular.module('app', ['ngFileUpload']);
app.controller('fileUploader', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
$scope.uploadFiles = function(file, errFiles) {
$scope.f = file;
$scope.errFile = errFiles && errFiles[0];
if (file) {
file.upload = Upload.upload({
url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
data: {file: file}
});
file.upload.then(function (response) {
$timeout(function () { // don't know why this timeout
$scope.fileReady = true;
file.result = response.data;
// can't figure out what to do with this!!!
console.log('response.data:\n', JSON.stringify(response.data.result, null, 2));
});
}, function (response) {
if (response.status > 0)
$scope.fileError = response.status + ': ' + response.data;
});
}
};
}]);
The response comes out as an object I can't do much with:
[
{
"fieldName": "file",
"name": "my-awesome-data.json",
"size": "364077"
}
]
How do I get the actual data that was uploaded / parse the JSON file?
Try to get the file content using $http.get like:
$http.get(response.data).success(function(data) {
console.log(data);
});
Related
I used the code below to upload Image and username to server. it works fine.
Now I want to return the username and filename in a console but it says this request has no response data available. I have tried to use a successcallback() function but still with no luck. it seems the issue is from the successcallback(). can someone help me fix that.
file.upload = Upload.upload({
method: 'post',
url: 'image.php',
data: {username: $scope.username, file: file},
}).then(function successCallback(response) {
alert(response.data[0].username);
alert(response.data[0].file);
console.log(response.data[0].username);
});
below is the entire code
//inject angular file upload directives and services.
var app = angular.module('fileUpload', ['ngFileUpload']);
app.controller('MyCtrl', ['$scope', 'Upload', '$timeout','$http', function ($scope, Upload, $timeout, $http) {
$scope.uploadPic = function(file) {
file.upload = Upload.upload({
url: 'upload.php',
data: {username: $scope.username, file: file},
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
console.log(response.data[0].username);
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
// Math.min is to fix IE which reports 200% sometimes
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
}]);
image.php
<?php
error_reporting(0);
$data = json_decode(file_get_contents("php://input"));
$username = strip_tags($data->username);
$return_arr[] = array("username"=>$username);
echo json_encode($return_arr);
exit();
The issue mentioned in the post above has been resolved.
I was sending the form parameter username as json_decode()
$data = json_decode(file_get_contents("php://input"));
$username = strip_tags($data->username);
Sending everything as post parameter solved my problem as in case below
$username = $_POST['username'];
Thanks
I would like to use this to show PDF in my SPA.
I tried to build a single example but it didn't work. Look this Plunker
http://plnkr.co/edit/nZAjYr?p=preview
In this example my pdf is in http://example.com/file.pdf
I really don't know where is the error, maybe it be in my controler:
angular.module('app', ['pdfjsViewer']);
angular.module('app').controller('AppCtrl', function ($scope, $http, $timeout) {
var url = 'http://example.com/file.pdf';
$scope.pdf = {
src: url, // get pdf source from a URL that points to a pdf
data: null // get pdf source from raw data of a pdf
};
getPdfAsArrayBuffer(url).then(function (response) {
$scope.pdf.data = new Uint8Array(response.data);
}, function (err) {
console.log('failed to get pdf as binary:', err);
});
function getPdfAsArrayBuffer (url) {
return $http.get(url, {
responseType: 'arraybuffer',
headers: {
'foo': 'bar'
}
});
}
});
Can anyone helpe me please?
Your controller should look something like this:
angular.module('app').controller('AppCtrl', function ($scope, $sce, $http, $timeout) {
var url = 'http://example.com/file.pdf';
PDFJS.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js'
$scope.pdf = {
src: $sce.trustAsResourceUrl(url), // get pdf source from a URL that points to a pdf
data: null // get pdf source from raw data of a pdf
};
});
Remove the unnecessary code and check the console for more details.
I am trying to use ng-file-upload to upload multiple files at the same time to my grails controller action. However, I can't figure out how to get a hold of the files that are being uploaded to the action.
Here is my JS code:
app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
$scope.uploadFiles = function (files) {
$scope.files = files;
if (files && files.length) {
Upload.upload({
url: 'http://localhost:8080/classifydemo/request/create',
data: {
files: files
}
}).then(function (response) {
$timeout(function () {
$scope.result = response.data;
});
}, function (response) {
if (response.status > 0) {
$scope.errorMsg = response.status + ': ' + response.data;
}
}, function (evt) {
$scope.progress =
Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
};
}]);
And my grails action is below:
class RequestController {
def create() {
request.headerNames.each{
println it
}
println params
println request.getFile("file")
render "test"
}
}
The above code fails on request.getFile.
Question
How can I get a hold of the files that are being uploaded to the controller so that I can process them in a loop.
Since you have the possibility of multiple files you should use:
request.fileNames.each {
MultipartFile file = request.getFile(it)
// do whatever you want with the file
}
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);
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);
}
};