AngularJS File Upload, uploaded image is blank? - angularjs

I'm using angular to upload file to parse.com rest api.
I follow this tutorial AngularJS Upload tutorialspoint and REST upload documentation here REST Upload
Then I modify my code. Here is my code looks like.
//below code inside RegisterController
$scope.upload = function () {
//upload file
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
console.log(file.name);
var uploadUrl = "http://128.199.249.233:1337/parse/files/"+file.name; //added file.name
fileUpload.uploadFileToUrl(file, uploadUrl);
//end upload file
}
//above code inside RegisterController
//below code outside any controller
rentalkika.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]);
});
});
}
};
}]);
rentalkika.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: {
'X-Parse-Application-Id': 'secret', //added this
'Content-Type': undefined
}
})
.success(function(response){
console.log(response);
})
.error(function(){
});
}
}]);
//above code outside any controller
Here is my HTML
<form ng-controller="RegisterController">
<label>Upload file</label>
<input type="file" name="ktp" file-model="myFile">
<label class="checkbox">
<input type="checkbox">Get hot offers via e-mail
</label>
<input type="submit" value="Sign up" class="btn btn-primary">
<input type="button" value="Upload" ng-click="upload()" class="btn btn-primary">
</form>
It successfully upload file indicated with 201 created status code and I get success response including name and image url.
The image looks like this blank image
Is something missing or wrong with my code?

It's happen because your binary data of image not sent.
Then I use this https://github.com/danialfarid/ng-file-upload and little bit configuration for headers.
And it works.

Related

Angularjs: Files upload within a table

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:

AngularJS: upload multiple images with multipart/form-data [duplicate]

This question already has an answer here:
AngularJS Upload Multiple Files with FormData API
(1 answer)
Closed 3 years ago.
Updated:
I'm facing 405 error upon uploading multiple files (images) via multipart/data-form. I'm able to send images in request and seems my payload showing correct boundries. But I'm getting empty response 405 on submit of API and response.status is showing 405 (method not allowed) error. I'm wondering what could be wrong as everything seems fine.
However i do suspect that there might be something to do with boundries in request-payload. I also come to know that browsers change MIME-TYPE when uploading and this conflicts with multipart/formData.
Please advise what could be wrong. Below is my code.
Directive (file-upload)
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]);
});
});
}
};
}]);
View (html)
<form ng-submit="submit()">
<input type="text" ng-model="for-param">
<input type="text" ng-model="for-param">
<input type="text" ng-model="for-param">
<input type="file" file-model="image01">
<input type="file" file-model="image02">
<button type="submit">Save</button>
</form>
Controller (on-submit)
$scope.submit = function () {
var params = {...};
var data = {
'frond-side-image' : $scope.image01,
'back-side-image': $scope.image02
};
var formData = new $window.FormData();
formData.append("image01", $scope.image01);
formData.append("image02", $scope.image02);
// Service
$http({
method: "POST",
url: "api-url",
headers: { "Content-Type": undefined },
params: params,
data: formData
}).then(function (response) {
console.log(response);
}, function (error) {
console.log(error);
});
};
Based on above config, following is my request & response
Header Request (after submit)
Content-Type: multipart/form-data; boundary=…--------------147472608521363
Request Payload
-----------------------------1363509831949
Content-Disposition: form-data; name="image01"
stacked_circles.png
-----------------------------1363509831949
Content-Disposition: form-data; name="image01"
stacked_circles.png
-----------------------------1363509831949--
Response
Based on above config I'm getting empty response, but I'm do getting 405 error which is method not allowed.
Please note that later on I'll convert image to base64 to upload on AWS (I'll just post image/base64 to backend than backend will upload it to AWS).
I've created JSFIDDLE for particular query.
Append the two images to the FormData object:
$scope.submit = function () {
var params = {};
var formData = new $window.FormData();
̶f̶o̶r̶m̶D̶a̶t̶a̶.̶a̶p̶p̶e̶n̶d̶(̶"̶f̶i̶l̶e̶"̶,̶ ̶d̶a̶t̶a̶)̶;̶
formData.append("file01", $scope.image01);
formData.append("file02", $scope.image02);
// Service
$http({
method: "POST",
url: "api-url",
headers: { "Content-Type": undefined },
params: params,
data: formData
}).then(function (response) {
console.log(response);
}, function (error) {
console.log(error);
});
};
When sending files, each file needs its own formData.append call.
Be sure to use the single file version of the file-model 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(){
̶m̶o̶d̶e̶l̶S̶e̶t̶t̶e̶r̶(̶s̶c̶o̶p̶e̶,̶ ̶e̶l̶e̶m̶e̶n̶t̶[̶0̶]̶.̶f̶i̶l̶e̶s̶)̶;̶
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
<form ng-submit="submit()">
<input type="file" file-model="image01">
<input type="file" file-model="image02">
<button type="submit">Save</button>
</form>

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