Send FormData with other field in AngularJS - angularjs

I have a form with two input text and one upload. I have to send it to the server but I have some problem concatenating the file with the text. The server expects this answer:
"title=first_input" "text=second_input" "file=my_file.pdf"
This is the html:
<input type="text" ng-model="title">
<input type="text" ng-model="text">
<input type="file" file-model="myFile"/>
<button ng-click="send()">
This is the Controller:
$scope.title = null;
$scope.text = null;
$scope.send = function(){
var file = $scope.myFile;
var uploadUrl = 'my_url';
blockUI.start();
Add.uploadFileToUrl(file, $scope.newPost.title, $scope.newPost.text, uploadUrl);
};
This is the Directive fileModel:
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]);
});
});
}
};
And this is the Service which call the server:
this.uploadFileToUrl = function(file, title, text, uploadUrl){
var fd = new FormData();
fd.append('file', file);
var obj = {
title: title,
text: text,
file: fd
};
var newObj = JSON.stringify(obj);
$http.post(uploadUrl, newObj, {
transformRequest: angular.identity,
headers: {'Content-Type': 'multipart/form-data'}
})
.success(function(){
blockUI.stop();
})
.error(function(error){
toaster.pop('error', 'Errore', error);
});
}
If I try to send, I get Error 400, and the response is: Multipart form parse error - Invalid boundary in multipart: None.
The Payload of Request is: {"title":"sadf","text":"sdfsadf","file":{}}

Don't serialize FormData with POSTing to server. Do this:
this.uploadFileToUrl = function(file, title, text, uploadUrl){
var payload = new FormData();
payload.append("title", title);
payload.append('text', text);
payload.append('file', file);
return $http({
url: uploadUrl,
method: 'POST',
data: payload,
//assign content-type as undefined, the browser
//will assign the correct boundary for us
headers: { 'Content-Type': undefined},
//prevents serializing payload. don't do it.
transformRequest: angular.identity
});
}
Then use it:
MyService.uploadFileToUrl(file, title, text, uploadUrl).then(successCallback).catch(errorCallback);

Here is the complete solution
html code,
create the text anf file upload fields as shown below
<div class="form-group">
<div>
<label for="usr">User Name:</label>
<input type="text" id="usr" ng-model="model.username">
</div>
<div>
<label for="pwd">Password:</label>
<input type="password" id="pwd" ng-model="model.password">
</div><hr>
<div>
<div class="col-lg-6">
<input type="file" file-model="model.somefile"/>
</div>
</div>
<div>
<label for="dob">Dob:</label>
<input type="date" id="dob" ng-model="model.dob">
</div>
<div>
<label for="email">Email:</label>
<input type="email"id="email" ng-model="model.email">
</div>
<button type="submit" ng-click="saveData(model)" >Submit</button>
directive code
create a filemodel directive to parse file
.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 code
append the file and fields to form data and do $http.post as shown below
remember to keep 'Content-Type': undefined
.service('fileUploadService', ['$http', function ($http) {
this.uploadFileToUrl = function(file, username, password, dob, email, uploadUrl){
var myFormData = new FormData();
myFormData.append('file', file);
myFormData.append('username', username);
myFormData.append('password', password);
myFormData.append('dob', dob);
myFormData.append('email', email);
$http.post(uploadUrl, myFormData, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
In controller
Now in controller call the service by sending required data to be appended in parameters,
$scope.saveData = function(model){
var file = model.myFile;
var uploadUrl = "/api/createUsers";
fileUpload.uploadFileToUrl(file, model.username, model.password, model.dob, model.email, uploadUrl);
};

You're sending JSON-formatted data to a server which isn't expecting that format. You already provided the format that the server needs, so you'll need to format it yourself which is pretty simple.
var data = '"title='+title+'" "text='+text+'" "file='+file+'"';
$http.post(uploadUrl, data)

This never gonna work, you can't stringify your FormData object.
You should do this:
this.uploadFileToUrl = function(file, title, text, uploadUrl){
var fd = new FormData();
fd.append('title', title);
fd.append('text', text);
fd.append('file', file);
$http.post(uploadUrl, obj, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
blockUI.stop();
})
.error(function(error){
toaster.pop('error', 'Errore', error);
});
}

Using $resource in AngularJS you can do:
task.service.js
$ngTask.factory("$taskService", [
"$resource",
function ($resource) {
var taskModelUrl = 'api/task/';
return {
rest: {
taskUpload: $resource(taskModelUrl, {
id: '#id'
}, {
save: {
method: "POST",
isArray: false,
headers: {"Content-Type": undefined},
transformRequest: angular.identity
}
})
}
};
}
]);
And then use it in a module:
task.module.js
$ngModelTask.controller("taskController", [
"$scope",
"$taskService",
function (
$scope,
$taskService,
) {
$scope.saveTask = function (name, file) {
var newTask,
payload = new FormData();
payload.append("name", name);
payload.append("file", file);
newTask = $taskService.rest.taskUpload.save(payload);
// check if exists
}
}

Assume that we want to get a list of certain images from a PHP server using the POST method.
You have to provide two parameters in the form for the POST method. Here is how you are going to do.
app.controller('gallery-item', function ($scope, $http) {
var url = 'service.php';
var data = new FormData();
data.append("function", 'getImageList');
data.append('dir', 'all');
$http.post(url, data, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function (response) {
// This function handles success
console.log('angular:', response);
}, function (response) {
// this function handles error
});
});
I have tested it on my system and it works.

Related

sending files via POST with AngularJS

I have a problem sending data via POST in angular,
my data include 2 files and some text field,
the problem is that the service doesn't receives any data.
this is my code:
var inputs = document.querySelectorAll( 'input[type="file"]' );
Array.prototype.forEach.call( inputs, function( input ){
input.addEventListener( 'change', function( e ){
if(this.id == "zipToUpload")
$scope.zipToUpload = this.files[0];
else
$scope.imgToUpload = this.files[1];
});
});
$scope.submit = function(){
var getInput = {nome: $scope.app_name, zipToUpload: $scope.zipToUpload, imgToUpload: $scope.imgToUpload, url: $scope.app_url,
secure: $scope.checkbox_pass, hide: $scope.checkbox_hide, beta: $scope.checkbox_beta, password: $scope.app_pass, location: "1" };
var req = {
method: 'POST',
url: 'api/rest/app/insert_app.php',
headers: {
'Content-Type': undefined
},
data: getInput
}
$http(req)
.then(function(result) {
console.log(result);
});
}
You can not directly upload file using model in angular. First you need a directive to bind files to the model.
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]);
});
});
}
};
}]);
And the input will be like :
<input type = "file" file-model = "myFile"/>
And the you can send post request using form data
$scope.upload = funtion(){
var fd = new FormData();
fd.append('file', $scope.myFile);
var req = {
method: 'POST',
url: 'api/rest/app/insert_app.php',
headers: {
'Content-Type': undefined
},
data: fd
}
$http(req)
.then(function(result) {
console.log(result);
});
}

Connection terminated parsing multipart data in Angulrjs and JAX-RS

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'.

is it possible to send uploaded file from angularjs to spring controller but by formbean

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

File upload with other data in angularjs with laravel

I want to upload file and other data with angularjs. I am usign FormData but I receive blank array from server side.
This is my form
<form ng-submit="beatSubmit()" name="beatform" enctype="multipart/form-data">
<input type="text" id="beat-name" ng-model="beatData.title" required="required" />
<input type="file" id="image" file-model="image" />
<input type="file" id="tagged_file" file-model="tagged_file" accept="audio/mp3" />
<input type="file" id="untagged-beat" file-model="untagged_file" accept="audio/mp3" />
<input type="text" class="form-control" id="price1" ng-model="beatData.price1">
</form>
Here is my Controller and FileModel directive
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 is controller part in another file
$scope.beatSubmit = function(){
var image = $scope.image;
var tagged_file = $scope.tagged_file;
var untagged_file = $scope.untagged_file;
var response = BEAT.uploadBeat($scope.beatData,image,tagged_file,untagged_file);
response.success(function(response){
console.log(response);
});
}
And this is my service
uploadBeat:function(data,image,tagged_file,untagged_file){
var fd = new FormData();
fd.append('image', image);
fd.append('tagged_file', tagged_file);
fd.append('untagged_file', untagged_file);
angular.forEach(data, function(value, key) {
fd.append(key,value);
});
console.log(fd); // fd is null , I don't know why?
var req = {
method: 'POST',
transformRequest: angular.identity,
url: 'api/upload_music',
data: fd,
headers:{
'Content-Type': undefined,
}
}
return $http(req);
}
When I tring to get these data from server side It will return null. I spent more time to resolve this But I didn't got any solution. If anyone know Please help me out. Thanks in advance.
Add this header details to the $http
$http({
method: 'POST',
url: '',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Accept':'*/*',
'Content-type':'application/x-www-form-urlencoded;charset=utf-8'
},
params:data,
timeout:4000
});
Laravel not allowed to submit ajax request without same domain policy
I found an error, I have to remove enctype="multipart/form-data" from form.

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

Resources