I used the AngularJS example provided in http://jsfiddle.net/JeJenny/ZG9re/ to upload a file from the local machine.
I work with angularJS(frontend) and symfony2(backend),and I have to send an email attachement(as a rest web service) but I have a problem,I didn't get any email attachment,this is the error that I get in the console:
this is my code:
<div ng-controller="MailNewCtrl1">
<input type="file" nv-file-select="" id="id_file" uploader="uploader" file-model="myFile" >
<button id="id_submit" class="btn btn-info w-xs" ng-click='usersend();'>send</button></div>
and this the controller:
'use strict';
angular.module('app', [
'ngAnimate',
'ngCookies',
'ngResource'
])
.controller('MailNewCtrl1', ['$scope', '$http' ,'fileUpload' , function($scope,$http,fileUpload) {
$scope.errors = [];
$scope.msgs = [];
$scope.usersend = function() {
$scope.errors.splice(0, $scope.errors.length); // remove all error messages
$scope.msgs.splice(0, $scope.msgs.length);
var file = $scope.myFile;
console.log('file is ' + JSON.stringify(file));
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl);
$http({method: 'POST', url: 'theURLsendMail?myFile='+file}).success(function(data, status, headers, config){
if (data.msg != '')
{
$scope.msgs.push(data.msg);
alert("sucess send");
}
else
{
$scope.errors.push(data.error);
}
}).error(function(data, status) { // called asynchronously if an error occurs
// or server returns response with an error status.
$scope.errors.push(status);
});
}
}]);
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.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(){
});
}
}]);
I even cheked the rights on the folder to store,it contains all the privilages
thanks for help
Related
I wish to send my localhost (in spring boot server) a selected image from the user using AngularJS and add data object in BD using JAX-RS.
-Code HTML:
<form role="form" enctype="multipart/form-data" name="myForm" ng-submit="uploadfile()">
<label class="control-label">Image:</label>
<input type="file" class="form-control " file-model="Image" >
<input type="text" class="form-control " ng-model="name" >
<input type="text" class="form-control " ng-model="lastname" >
<button type="submit"> save</button>
</form>
--code AngularJS;
var app = angular.module('Mainapp', ['ngRoute','file-model','ui.bootstrap']);
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.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
//fd.append('file', file);
angular.forEach(file, function(file) {
fd.append('file', file);
});
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function(response) {
console.log("done post "+response);
}).catch(function(e) {
console.log('failed to post: ', e);
throw e;
})
}
}]);
//upload file and data object of user
$scope.uploadfile = function() {
var file = $scope.Image;
console.dir(file);
var uploadUrl ="http://localhost:8000/auditconfig/images/"+file.name;
fileUpload.uploadFileToUrl(file, uploadUrl); // error here "failed to post"
var user = {
name: $scope.name,
lastname: $scope.lastname,
image:file.name
};
$http.post(url+"/add", user) //The user is added to the database
.success(function(data) {
$scope.ListUsers = data;
}).error(function(err, data) {
console.log("error: " +data);
});
};
-After a test of the "uploadfile ()", I get the following results:
//**console.dir(file);
*File:
lastModified:1490260924299
lastModifiedDate; Thu Mar 23 2017 10:22:04 GMT+0100 (Paris, Madrid)
name:"01.png"
size:1637
type:"image/png"
webkitRelativePath:""
__proto__:File
-Test of upload file:
//**console.log('failed to post: ', e);
Failed to load resource: the server responded with a status of 500 (Internal Server Error) :8099/AuditConf/images/01.png
failed to post: Object
Config:Objectd
ata:FormData
__proto__:FormData
headers:Object
Accept:"application/json, text/plain, */*"
Content-Type:undefined
__proto__:Object
method:"POST"
transformRequest:function identity($)
transformResponse:Array(1)
url:"http://localhost:8099/AuditConf/images/Exception--JAX-RS.png"
__proto__:Object
data:Object
error:"Internal Server Error"
exception:"java.lang.RuntimeException"
message:"java.io.IOException: UT000036: Connection terminated parsing multipart data"
path:"/auditconfig/images/Exception--JAX-RS.png"
status:500
timestamp:1490778930961
__proto__:Object
headers:function (name)
status:500 statusText
:"Internal Server Error"
__proto__;Object
The solution is:
var app = angular.module('Mainapp', ['ngRoute','file-model','ui.bootstrap']);
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]);
});
});
}
};
}]);
this.uploadFileToUrl = function(file, uploadUrl){
var data = new FormData();
data.append('file', file);
return $http.post(uploadUrl, data, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}).then(function (results) {
return results;
});
}
//upload file and data object of user
$scope.uploadfile = function() {
var file = $scope.Image;
console.dir(file);
//URL of API not path of floder
var uploadUrl ="http://localhost:8000/auditconfig/UpFile";
fileUpload.uploadFileToUrl(file, uploadUrl);
var user = {
name: $scope.name,
lastname: $scope.lastname,
image:file.name
};
$http.post(url+"/add", user)
.success(function(data) {
$scope.ListUsers = data;
}).error(function(err, data) {
console.log("error: " +data);
});
};
Try this:
this.uploadFileToUrl = function(file, uploadUrl){
var data = new FormData();
data.append('file', file);
//Comment below
//angular.forEach(file, function(file) {
// fd.append('file', file);
//});
return $http.post(uploadUrl, data, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}).then(function (results) {
return results;
});
}
See the answers here which accepts multiple files within one object 'file'.
I have form having text field and file type. I want to send this to controller using form bean. here is my code.following is my js file. from where I'm sending multipart file.
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, uploadform) {
var fd = new FormData();
fd.append('file', file);
fd.append("jsondata", JSON.stringify(uploadform));
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function () {
})
.error(function () {
});
}
}]);
myApp.controller('myFileUpload', ['$scope', 'fileUpload', function ($scope, fileUpload) {
$scope.uploadFile = function () {
var file = $scope.myFile;
$scope.uploadform = {};
var uploadUrl = "navigation/uploadexcel";
fileUpload.uploadFileToUrl(file, uploadUrl, $scope.uploadform);
};
}]);
and my controller is..I want to map multipart file and textbox value into firmbean first and from that I want to get my file for further process.
#RequestMapping(value = "/uploadexcel", method = RequestMethod.POST)
public #ResponseBody
String upload(#RequestBody EmployeeFormBean fb) {
String res = null;
try {
MultipartFile f = fb.getFile();
System.out.println("-->"+ f.getOriginalFilename());
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
my jsp code is as following
<div style="background-color: blanchedalmond">
<div ng-controller = "myFileUpload">
<input type="file" file-model="myFile"/>
<input type="text" name="template" ng-model="uploadform.templateName"/>
<button ng-click="uploadFile()">upload me</button>
</div>
</div>
but m getting error as follow...
415 Unsupported Media Type
59ms
angular...DF52B9C (line 103)
HeadersPostResponseHTMLCookies
"NetworkError: 415 Unsupported Media Type - http://localhost:8080/crmdemo1/navigation/uploadexcel"
how to resolve this issue. I dont want to do it by #resuestparam("file")
is it possible to do this using formbean.. and if yes please tell me how can I do it?
You have a problem in the content type of your request, try to add headers = "content-type=multipart/*" , consumes = "application/json" to #RequestMapping. Beside that (in your service fileUpload) change the headers: {'Content-Type': undefined} to headers: {'Content-Type': application/json}. Hope this will help you
I am fresher to using Angular js and node js. I am doing File Uploading process by angular and node js. I already create directives and services by watching some tutorial. But in services Form data is not posting on NodeJs server. Here is following code file by file:-
Here is my Directive :-
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]);
});
});
}
};
}]);
Here is service file code :-
myApp.service('multipartForm', ['$http', function($http){
this.post = function(uploadUrl, data){
var fd = new FormData();
for(var key in data)
fd.append(key,data[key]);
console.log(fd);
$http({
url: uploadUrl,
method: 'POST',
headers: { 'Content-Type': undefined },
transformRequest: angular.identity,
data: JSON.stringify(fd)
}).
success(function(data) {
console.log('success');
}).
error(function(data, response) {
console.log(response + " " + data);
});
};
}]);
This is my angularjs code where i defined all methods :-
var myApp = angular.module('myApp', []);
myApp.controller('saveJsonDemo',['$http','$scope','multipartForm',function($http,$scope,multipartForm){
$scope.formData = {};
$scope.saveJson = function() {
var uploadUrl = '/savedata';
console.log($scope.formData);
multipartForm.post(uploadUrl, $scope.formData);
};
}]);
When i post data though this service to node js server, and i console.log req.body and rex.files is becomes blank. Where is the problem in my code. Here is my Node js server file (app.js)
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var path = require('path');
var http = require('http');
var fs = require('fs');
var multer = require('multer');
var done = false;
// all environments
app.use(multer({dest: './uploads/'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.set('port', process.env.PORT || 3000);
app.use(function(err, req, res, next){
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json({limit: '50mb'}));
console.log(err);
});
app.post('/savedata', function(req,res){
console.log('Here');
console.log(req.body);
var currentTime = Date.now();
/*fs.writeFile('./json/'+currentTime+'.json', JSON.stringify(req.body), function (err) {
if (err) return console.log(err);
else res.send();
}); */
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
On the above /savedata method req is coming blank. Where is the mistake in my code.
http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
<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 ' );
console.dir(file);
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
</script>
simply copy paste and change your api path in url required for angular service calling from controller then it will work :)
I followed this tutorial to image upload for ionic app.
https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs
It works but I have one issue: in the file upload, I am returning the new filename from the server. I have to save it to a variable in the controller. I can't save the value from services to controller.
Here is my controller, services and views
Directive & Service
.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]);
});
});
}
};
}])
.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(data){
alert(data);
})
.error(function(){
});
}
}])
Controller
.controller('MyCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadBtn1 = false;
$scope.uploadSpin1 = true;
$scope.uploadFile = function(){
var file = $scope.myFile;
$scope.uploadBtn1 = true;
$scope.uploadSpin1 = false;
console.log('file is ' + JSON.stringify(file));
var uploadUrl = "http://example.com/app/upload.php";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
HTML
<input type="file" file-model="myFile"/>
<button type="button" ng-click="uploadFile()"
ng-hide="uploadBtn1" class="ng-hide">upload me</button>
<ion-spinner icon="ios-small" ng-hide="uploadSpin1" class="ng-hide"></ion-spinner>
I also added the loading spinner when the upload starts and I want to hide it when the upload ends.
Thanks
I have made a few changes to the example in question. The service is now implemented as a factory which returns a promise.
You can then wait in your controller for the promise to return and then handle the data in your controller.
codepen example
var uploadFile = fileUpload.uploadFileToUrl(file, uploadUrl);
uploadFile.error(function(data){
alert('data returned - handle me', data);
});
In my example, I have changed the returned data to a string and passed this back to the controller which then alerts the user of this data.
Please see the following code and let me know how can i upload the file in a folder of my project..
where can i write the url? I select the file and it does not get save simply by clicking on the update button.
Thanks in Advance
Ria
var DocTrack = angular.module('DocTrack', []);
DocTrack.controller('DocumentController', DocumentController);
DocTrack.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]);
});
});
}
};
}]);
DocTrack.service('fileUpload', ['$http', function ($http) {
debugger;
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 () {
alert('File Uploaded Successfully...');
})
.error(function () {
alert('File has not been uploaded');
});
}
}]);
DocTrack.controller('DocumentController', ['$scope', 'fileUpload', function ($scope, fileUpload) {
$scope.uploadFile = function () {
debugger;
var file = $scope.myFile;
console.log('file is ' + JSON.stringify(file));
var uploadUrl = "http://localhost:40966/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
<div ng-controller = "DocumentController">
<input type="file" file-model="myFile" />
<button ng-click="uploadFile()" data-url="">upload me</button>
</div>
var uploadUrl = "http://localhost:40966/fileUpload";
Can you check your backend url it must be same as you specify and during saving your image you must specify your path to store image in backend.
In html form
<div class="form-group col-xs-12 ">
<label class="form-group">Select file</label>
<div class="controls">
<input type="file" file-model="fileUrl"/>
</div>
</div>
in Controller.js you put following code
var file = $scope.fileUrl;
var uploadUrl = "/Uploadfile";
var data = fileUpload.uploadFileToUrl(file, uploadUrl,formdata);
};
In your service
.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl,formdata){
var fd = new FormData();
fd.append('file', file);
fd.append('formdata',angular.toJson(formdata));
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(data){
console.log(data);
return data;
})
.error(function(){
});
}
}]);
.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]);
});
});
}
};
}])
"/Uploadfile" is your backend url