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);
})
}
}
});
Related
Our team is developing in ServiceNow and created a table widget that needs the ability to upload files per row. Our code for the file upload consist of the following code:
In our controller, we have the following:
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
We also created a dependency called fileUpload:
var myApp = angular.module('myApp', []);
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(){
});
};
}]);
Finally, we have an angular provider called fileModel:
function fileModel($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);
});
});
}
};
}
The issue we're running into is when we contain the following within <td> tags:
<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>
When the above code is out side of the <td> tags, we are able to view the attached files in our console:
Once the <input> is contained within <td>, myFile does not exist in the console. What do we need to do in order for each row of our table to have its own attachments? This is what our table looks like:
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'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
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
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();