Cannot upload file and its details with AngularJS - angularjs

i'm trying to upload image file along with it's details information with AngularJS. The file's details will be stored in JSON file on the server. But, it doesn't work. the return info from the server is just an empty array. I have no idea why my code doesn't work. I to experiment with Content-type, etc, etc... but still no luck.
my code:
<body>
<div>
<form ng-controller="Ctrl" ng-submit="save()">
Title :<input type="text" ng-model="file_details.title"><br>
Summary: <input type="text" ng-model="file_details.summary"><br>
File: <input type="file" file-upload><br>
<button type="submit">save</button>
</form>
</div>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/angular/angular.min.js"></script>
<script>
//Angular here
(function(){
var app = angular.module('myApp', []);
app.config(function($httpProvider){
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
app.controller('Ctrl', ['$scope', '$http', function($scope, $http){
$scope.file_details = {};
$scope.files = [];
//listening from fileUpload directive
$scope.$on('fileSelected', function(event, args){
$scope.$apply(function(){
//add the file object to scope's files collection
$scope.files.push(args.file);
});
});
$scope.save = function(){
$http({
method: 'POST',
url: 'process.php',
transformRequest: function (data) {
var formData = new FormData();
formData.append("file_details", angular.toJson(data.file_details));
formData.append("file", data.files);
},
headers: {
'Content-Type': false
},
data: {
file_details: $scope.file_details,
files: $scope.files
}
}).success(function (data, status, headers, config) {
// alert("success!");
console.log(data);
});
}
}]);
app.directive('fileUpload', function(){
return{
link: function(scope, elm, attrs){
elm.bind('change', function(event){
var files = event.target.files;
scope.$emit('fileSelected', { file: files });
});
}
}
});
})();
</script>
</body>
My server code (just to check if the data is sent, but it still returning an empty array):
print_r($_POST); die();

Related

AngularJS unable to perform file upload [duplicate]

This question already has answers here:
AngularJS Unable to display upload file logs [duplicate]
(1 answer)
ng-model for `<input type="file"/>` (with directive DEMO)
(13 answers)
Closed 3 years ago.
I am doing a file upload in angularjs. I am unable to get the file object content before sending to my back-end.
XHR, headers:
XHR-Header
I have no idea why because I can get the content in my logs.
console.log:
logs
These are my codes:
html:
<body ng-app="myApp" ng-controller="appCtrl">
<input type="file" id="file" name="files" accept="text/*"
data-url="file" class="inputfile_upload" select-ng-files
ng-model="uploadedFile"/>
<label for="file"> <span id="chooseFile"></span>Upload a file!</label>
<button id="submitBtn" type="submit" ng-click="upload()">Upload</button>
</body>
controller.js:
var app = angular.module('myApp', [])
app.controller('appCtrl', function ($scope, $rootScope, $http, fileUploadService){
$scope.upload = function() {
var file = $scope.uploadedFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "/uploaded_file";
fileUploadService.uploadFileToUrl(file, uploadUrl);
};
}
service.js:
app.factory('fileUploadService', function ($rootScope, $http) {
var service = {};
service.uploadFileToUrl = function upload(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function successCallback(response){
console.log("Files added");
}, function errorCallback(response){
console.log("Files not successfully added");
})
}
return service;
});
directive.js:
app.directive("selectNgFiles", function($parse) {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});

How to update data with image using AngularJS $http.put Method

I am created a Laravel application to upload data with image.I am successfully done this task using following way in AngularJs
app.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
app.controller('rowController', function($scope,$http,$modal,Row){
$scope.saveItem=function(){
var fd = new FormData();
//fd.append('photo', $scope.myFile);
for(var key in $scope.newrow)
fd.append(key,$scope.newrow[key]);
$http.post('/api/row_material', fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(data,status,headers,config){
console.log(data);
}).error(function(data,status,headers,config){
console.log(data);
});
}
}
Above POST method successfully worked for me.Now I need to update data with image using $http.put() method.I am created a method as listed below;
$scope.updateItem=function(){
var fd = new FormData();
for(var key in $scope.newrow)
fd.append(key,$scope.newrow[key]);
var uri='api/row_material/1';
$http.put(uri,fd,{headers: '{"Content-Type": undefined}'} )
.success(function (data, status, headers, config) {
alert('Updated Successfully.');
})
.error(function (data, status, header, config) {
alert('Server error');
console.log(data);
});
}
But above put method causes an error given below;
<!DOCTYPE html>
<html>
<head>
<meta name="robots" content="noindex,nofollow" />
<style>
/* Copyright (c) 2010, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html */
html{color:#000;background:#FFF;}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0;}table{border-collapse:collapse;border-spacing:0;}fieldset,img{border:0;}address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}li{list-style:none;}caption,th{text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym{border:0;font-variant:normal;}sup{vertical-align:text-top;}sub{vertical-align:text-bottom;}input,textarea,select{font-family:inherit;font-size:inherit;font-weight:inherit;}input,textarea,select{*font-size:100%;}legend{color:#000;}
html { background: #eee[…]
Above put method work with out using FormDate() using following way.But Image not uploaded to server
$scope.updateItem=function(){
var uri='api/row_material/1';
$http.put(uri,$scope.newrow,{headers: '{"Content-Type": undefined}'} )
.success(function (data, status, headers, config) {
alert('Updated Successfully.');
})
.error(function (data, status, header, config) {
alert('Server error');
console.log(data);
});
}
I need your help to update data with image using FormData put method in AngularJS
I would suggest you to use ng file upload plugin. I'm not sure what you are using on the backend but this plugin will help you to send file that is selected from input tag with your data. Check all their demo to get a clear idea.
https://github.com/danialfarid/ng-file-upload
Thanks.
There are several good approaches for this..
One of them is the one given below..
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
<div ng-app = "myApp" ng-controller = "myCtrl">
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>
</div>
This would do for the client side. Now for the server side, you need to write a script that can handle the uploaded image correctly and place it on the destination where you intend to..
This piece from the PHP documentation discusses the PUT method and file uploads (multipart/form-data).
I can't quote any parts from it because I think everything is important. You should read it in detail but to summarize it's not possible without changes to your Apache configuration and creation of auxiliary scripts.
With Laravel you should use [Form Method Spoofing][2] (basically a variable called _method) and keep on using POST. The _method will allow you to call Laravel's PUT action correctly.

fileupload in angularjs produces an error

I'm trying to use a simple file upload using angularjs, but the Upload and Close buttons are not working.
Here is my html:
<div>
<div class="modal-header">
<h3 class="modal-title">File Attachment</h3>
</div>
<div class="modal-body">
<input type="file" file-model="myFile" />
</div>
<div class="modal-footer">
<div class="btn-toolbar pull-right" role="toolbar">
<div class="btn-group" role="group" ng-controller="FileUploadController as fileUploadCtrl">
<button class="btn btn-default" ng-click="FileUploadCtrl.uploadFile()">Upload</button>
</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-default" ng-click="$close()">Close</button>
</div>
</div>
</div>
</div>
In addition, I am getting an error in my factory even before I hit the browse button that states the following, but cannot find a solution for it on the web even though I see many questions about it.
[$injector:undef] Provider 'fileUpload' must return a value from $get factory method.
Here is my factory method:
.factory('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function (file, uploadUrl) {
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
})
.success(function () {
})
.error(function () {
});
}
}])
Here is my directive:
.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function () {
scope.$apply(function () {
modelSetter(scope, element[0].files[0]);
});
});
}
};
}])
Here is my js file function:
module.controller('FileUploadController', ['$scope', 'fileUpload', function ($scope, fileUpload)
{
$scope.uploadFile = function ()
{
var file = $scope.myFile;
console.log('file is ');
console.dir(file);
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}])
Note that I need to use a factory and directive since this file attachment functionality will be used across multiple forms.
From what the error message says, it looks like I need to return a value from the factory method, but don't know what....
Can someone please tell me how I can accomplish the file uploading here and what I'm doing wrong?
Use factory like this
.factory('fileUpload', ['$http', function ($http) {
return
{
uploadFileToUrl : function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}
}]);
or if you want instead of factory you can use 'service'
.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
for more detail you can check this link : AngularJS: Service vs provider vs factory

How resolve 404 error in multipart file upload?

I'm trying to implement a simple file upload function using AngularJs and Spring RESTful web services.
HTML
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>File Upload Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="js/myuploadfunction.js"></script>
</head>
<body ng-app="myAp">
<h1>File Upload</h1>
<div ng-controller = "myCtrl">
<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>
</div>
</body>
</html>
JS
var myApp = angular.module('myAp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "upload";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
REST
#RequestMapping(value="/upload", method = RequestMethod.POST)
public #ResponseBody void upload(#RequestBody MultipartFile file) {
System.out.println(file.getName());
}
When I run, I get this - POST http://localhost:8080/File/upload 404 (Not Found).
I'm following http://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs for script reference. Any help on this?
As far as I remember, I used MultipartFile as a #RequestParam not a #RequestBody
and the name should match the <input> tag's "name" attribute.
see http://spring.io/guides/gs/uploading-files/

AngularJs File Upload

I try to upload a file using Angularjs but ends up with error
<!DOCTYPE html>
<html ng-app = "myApp">
<body>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<div ng-controller = "myCtrl">
<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' + JSON.stringify(file));
var uploadUrl = "E:\Backup";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
</script>
</body>
</html>
When i run the above code I got the following error
file is {"webkitRelativePath":"","lastModifiedDate":"2014-04-10T13:01:34.000Z","name":"gvxgfg.txt","type":"text/plain","size":95912} test.html:48
XMLHttpRequest cannot load file:///E:/Backup. Cross origin requests are only supported for HTTP. angular.js:8165
Error: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///E:/Backup'.
at Error (native)
at b (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:76:389)
at t (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:72:120)
at $get.h (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:70:91)
at l.promise.then.H (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:97:5)
at l.promise.then.H (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:97:5)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:98:173
at h.$get.h.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:108:40)
at h.$get.h.$digest (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:105:331)
at h.$get.h.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:108:370)
I am just a beginner. I dont know where i went wrong. Hope some one resolves. Thanks in Advance

Resources