Im trying to find a way to upload some parameters along with a file using FormData but not sure where to look for it on the backend.
HTML:
<input type="file" file-model="myFile"/>
<button class="btn" ng-click="uploadFile()">upload</button>
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]);
});
});
}
};
}])
Controller:
var file = $scope.aFile;
var foo = 'bar';
var fd = new FormData();
fd.append('file', file);
fd.append('foo', foo);
$http.post(api, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function(res){
console.log(res.data);
});
Backend:
$_POST = json_decode(file_get_contents('php://input'),true);
$result = saveFile('./img/', 'a_test_file'); /* SUCCEEDS! */
$res = array($_POST, $_FILES, $result); /* $_POST empty, $_FILES ok, $result success */
/* where is foo?? */
Not sure what Im missing or where to look for the additional parameter?
Related
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);
});
}
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 use angularJS directive to get file to upload and I use the directive like this way:
<input type="file" file-model="myFile">
The directive looks like this:
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('fileUploadService', ['$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(){
console.log('file upload successful');
})
.error(function() {
console.log('file upload error');
});
}
}]);
In controller:
$scope.uploadFile = function() {
var file = $scope.myFile;
if (typeof file != 'undefined' && file != null) {
console.log('file is ' + file);
console.dir(file);
var uploadUrl = "/upload";
fileUpload.uploadFileToUrl(file, uploadUrl);
}
};
The upload works fine. I would have two questions concerning improvements of this upload:
how to upload more than one file - is there a possibility to upload more than one file with this directive
if file was uploaded - how to
how to upload more than one file - is there a possibility to upload more than one file with this directive
You must set multipleon your input field to be able to select multiple files. Then, your file variable will be an array of several files(if several files were chosen) instead of just a File object.
if file was uploaded - how to
... ?
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