Upload file from AngularJS controller to Spring writtin in Kotlin - angularjs

There are a few similar questions already on StackOverflow. I have gone through some of them, but they did not work for me. So please do not mark this question as duplicate.
I want to upload a file using AngularJS to Spring Controller written in Kotlin. I have written the code below in order to do so, but it does not work. I get a 404 bad request response with a message that Required request part 'file' is not present
Input
<form class="col-xs-12 col-sm-4 form-inline " ng-submit="$ctrl.saveFiles()">
<div class="form-group">
<label for="file-upload" class="custom-file-upload">
Choose File
</label>
<input id="file-upload" type="file" file-model="$ctrl.file" name="file"/>
</div>
<div class="form-group">
<button class="btn btn-primary pull-right" type="submit">Submit</button>
</div>
</form>
file-model 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]);
});
});
}
};
}])
I have copied this directive from this question
$ctrl.saveFiles() function
$ctrl.saveFiles = function () {
// var file = document.getElementById("file-upload").files[0]
var formData = new FormData();
formData.append("file", $ctrl.file);
console.log(formData.has("file")); // true
var url = '/upload',
config = {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
};
return $http.post(url, formData, config)
};
Spring #bean
#Bean
open fun multipartResolver(): MultipartResolver {
val multipartResolver = CommonsMultipartResolver()
multipartResolver.setMaxUploadSize(500000000)
return multipartResolver
}
Spring #PostMapping method
#PostMapping(value = "/upload")
#Throws(Exception::class)
fun uploadFile(#RequestParam("file") file: MultipartFile): String {
return "Upload file"
}
Request header
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 4829202
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryJ8BRhjvMRLt9UdRS
As you see though I use Kotlin, It is totally fine to answer in Java.

This was my first time uploading a file using AngularJS and Spring. There are some who uses CommonsMultipartResolver. I had done so. However, I did not need to use it.
It was due to using CommonsMultipartResolver that I could not upload file. I removed the code below and it works as expected. However, for some reason, I can not upload as large files as an unsplash photo
#Bean
open fun multipartResolver(): MultipartResolver {
val multipartResolver = CommonsMultipartResolver()
multipartResolver.setMaxUploadSize(500000000)
return multipartResolver
}

Related

AngularJS: 405 error on uploading multiple images with multipart/form-data

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 data (boundaries). But I'm getting empty response 405 on (API) submit 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 this 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 I'm getting empty response, but I'm do getting 405 error which is method not allowed.
following is my Request Headers & Payloads
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--
In addition I also have tried to do this with XMLHttpRequest() and with that I'm also getting same 405 error with empty response.
var request = new XMLHttpRequest();
request.open('POST', url);
request.setRequestHeader('Content-Type', undefined);
request.send(formData);
Ref: stackoverflow
I'm now going to try with $ngResource and see if it can solve my issue.
Note: This API is working fine in POSTMAN
Note: Backend is in JAVA (spring)
Note: 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).

How to send file to Sails from AngularJS without using custom directives?

So I need to upload an image to the server. Right now it works only with a POST request made via HTML. But I need to send other data and do other stuff before uploading it, so I'd like to send the request inside an Angular controller, using $http.post(...). I've seen some really complex solutions using custom directives, but I'd like to know if there's anyway to do something straight forward like:
$scope.uploadPhoto = function(){
var fd = new FormData();
fd.append("uploadFile", $scope.file);
$http.post('file/upload', fd);
}
Working code:
HTML:
<form id="uploadForm"
enctype="multipart/form-data"
action="/file/upload"
method="post">
<input type="file" name="uploadFile" />
<input type="submit" value="submit"/>
</form>
Sails Controller:
upload: function (req, res) {
var uploadFile = req.file('uploadFile');
uploadFile.upload(
{ dirname: '../../assets/images',
saveAs: function(file, cb) {
cb(null, file.filename);
}
}, function onUploadComplete (err, files) {
if (err) return res.serverError(err);
res.json({status:200,file:files});
});
}

Send formdata using angularjs http service

I have to submit user form data. I have done this by using ajaxSubmit but its add one more new JS file into my application. I want to get this done by using angularjs http service. My question is that by using ajaxSubmit I need to send userId id request body and the form data is handle by the ajaxSubmit method itselft. I just want to send the data in a way that ajaxSubmit is doing.
HTML
<form role="form" action="profile_pic">
<div class="cover-50 pull-left pos-relative upload-photo">
<input type="file" onchange="angular.element(this).scope().uploadProfilePic(this)" accept="images/*" capture>
<label>Upload Media</label>
</div>
</form>
Controller
$scope.uploadProfilePic = function(){
$http({
'method': 'POST',
'url': /upload/user/image,
'data': {
'userId' : 457
},
});
// $form.ajaxSubmit({
// type : 'POST',
// url : '/upload/user/image',
// data : {
// 'userId' : 457
// }
// });
}
You could use FormData() to append additional properties to send through $http post.
var data = new FormData();
data.append('userId', 457);
data.append('file', uploadFileUrl);
data.append('abc', "XYZ");
return $http.post('/upload/user/image', data, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}).then(function (results) {
//results.data
});

Upload multipart form data with filename in Request Payload

I am still confused about different method of uploading files. The backend server is not under my control but I can upload a file using Swagger page or Postman. That means the server is functioning OK. But when I use AngularJS to do the upload, it doesn't work.
Here is what works using Postman to test. I am just using form-data:
Notice that Request Headers has Content-Type as multipart/form-data. But the Request Payload has filename and Content-Type as image/png.
Here is my code:
$http({
method: 'POST',
url: ApiUrlFull + 'Job/Item?smartTermId=0&name=aaa1&quantity=1&ApiKey=ABC',
headers: { 'Content-Type': undefined },
transformRequest: function(data) {
var fd = new FormData();
fd.append('file', params.imageData);
return fd;
}
})
params is just an object with file url in imageData.
My code also send similar URL params (so we can ignore that causing issues). But the Request Payload is base64 and it looks different as it is missing the filename field.
I have zero control of the backend and it is written in .NET.
So I guess my question is: Using Angular (either $http or $resource), how do I modify the request so that I am sending the correct Request Payload as how Postman does it? I cannot figure out how to reverse engineer this.
I have tried this https://github.com/danialfarid/ng-file-upload and it actually did OPTIONS request first before POST (assuming CORS issue). But the server gave 405 error for OPTIONS.
You can use something along the line of:
<input type="file" name="file" onchange="uploadFile(this.files)"/>
And in your code:
$scope.uploadFile = function(files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);
var uploadUrl = ApiUrlFull + 'Job/Item?smartTermId=0&name=aaa1&quantity=1&ApiKey=ABC';
$http.post(uploadUrl, fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success( ...all right!... ).error( ..damn!... );
};
My need was a follows.
In the form there is a default picture.
Clicking the picture opens a file select window.
When the user selects a file, it is uploaded right away to the server.
As soon as I get a response that the file is valid display the picture to the user instead of the default picture, and add a remove button next to it.
If the user clicks on an existing picture, the file select window reopens.
I tried to use a few code snippets on github that didn't solve the problem, but guided me in the right way, And what I ended up doing is as so:
Directive
angular.module("App").directive('fileModel', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.files = {};
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
// I wanted it to upload on select of file, and display to the user.
element.bind('change', function () {
scope.$apply(function () {
modelSetter(scope, element[0].files[0]);
});
// The function in the controller that uploads the file.
scope.uploadFile();
});
}
};
});
Html
<div class="form-group form-md-line-input">
<!-- A remove button after file has been selected -->
<span class="icon-close pull-right"
ng-if="settings.profile_picture"
ng-click="settings.profile_picture = null"></span>
<!-- Show the picture on the scope or a default picture -->
<label for="file-pic">
<img ng-src="{{ settings.profile_picture || DefaultPic }}"
class="clickable" width="100%">
</label>
<!-- The actual form field for the file -->
<input id="file-pic" type="file" file-model="files.pic" style="display: none;" />
</div>
Controller
$scope.DefaultPic = '/default.png';
$scope.uploadFile = function (event) {
var filename = 'myPic';
var file = $scope.files.pic;
var uploadUrl = "/fileUpload";
file('upfile.php', file, filename).then(function (newfile) {
$scope.settings.profile_picture = newfile.Results;
$scope.files = {};
});
};
function file(q, file, fileName) {
var fd = new FormData();
fd.append('fileToUpload', file);
fd.append('fn', fileName);
fd.append('submit', 'ok');
return $http.post(serviceBase + q, fd, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}).then(function (results) {
return results.data;
});
}
Hope it helps.
P.S. A lot of code was striped from this example, if you need clarification just comment.

AngularJS: how to implement a simple file upload with multipart form?

I want to do a simple multipart form post from AngularJS to a node.js server,
the form should contain a JSON object in one part and an image in the other part,
(I'm currently posting only the JSON object with $resource)
I figured I should start with input type="file", but then found out that AngularJS can't bind to that..
all the examples I can find are for wraping jQuery plugins for drag & drop. I want a simple upload of one file.
I'm new to AngularJS and don't feel comfortable at all with writing my own directives.
A real working solution with no other dependencies than angularjs (tested with v.1.0.6)
html
<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>
Angularjs (1.0.6) not support ng-model on "input-file" tags so you have to do it in a "native-way" that pass the all (eventually) selected files from the user.
controller
$scope.uploadFile = function(files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);
$http.post(uploadUrl, fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success( ...all right!... ).error( ..damn!... );
};
The cool part is the undefined content-type and the transformRequest: angular.identity that give at the $http the ability to choose the right "content-type" and manage the boundary needed when handling multipart data.
You can use the simple/lightweight ng-file-upload directive.
It supports drag&drop, file progress and file upload for non-HTML5 browsers with FileAPI flash shim
<div ng-controller="MyCtrl">
<input type="file" ngf-select="onFileSelect($files)" multiple>
</div>
JS:
//inject angular file upload directive.
angular.module('myApp', ['ngFileUpload']);
var MyCtrl = [ '$scope', 'Upload', function($scope, Upload) {
$scope.onFileSelect = function($files) {
Upload.upload({
url: 'my/upload/url',
file: $files,
}).progress(function(e) {
}).then(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
});
}];
It is more efficient to send a file directly.
The base64 encoding of Content-Type: multipart/form-data adds an extra 33% overhead. If the server supports it, it is more efficient to send the files directly:
$scope.upload = function(url, file) {
var config = { headers: { 'Content-Type': undefined },
transformResponse: angular.identity
};
return $http.post(url, file, config);
};
When sending a POST with a File object, it is important to set 'Content-Type': undefined. The XHR send method will then detect the File object and automatically set the content type.
To send multiple files, see Doing Multiple $http.post Requests Directly from a FileList
I figured I should start with input type="file", but then found out that AngularJS can't bind to that..
The <input type=file> element does not by default work with the ng-model directive. It needs a custom directive:
Working Demo of "select-ng-files" Directive that Works with ng-model1
angular.module("app",[]);
angular.module("app").directive("selectNgFiles", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<h1>AngularJS Input `type=file` Demo</h1>
<input type="file" select-ng-files ng-model="fileArray" multiple>
<h2>Files</h2>
<div ng-repeat="file in fileArray">
{{file.name}}
</div>
</body>
$http.post with content type multipart/form-data
If one must send multipart/form-data:
<form role="form" enctype="multipart/form-data" name="myForm">
<input type="text" ng-model="fdata.UserName">
<input type="text" ng-model="fdata.FirstName">
<input type="file" select-ng-files ng-model="filesArray" multiple>
<button type="submit" ng-click="upload()">save</button>
</form>
$scope.upload = function() {
var fd = new FormData();
fd.append("data", angular.toJson($scope.fdata));
for (i=0; i<$scope.filesArray.length; i++) {
fd.append("file"+i, $scope.filesArray[i]);
};
var config = { headers: {'Content-Type': undefined},
transformRequest: angular.identity
}
return $http.post(url, fd, config);
};
When sending a POST with the FormData API, it is important to set 'Content-Type': undefined. The XHR send method will then detect the FormData object and automatically set the content type header to multipart/form-data with the proper boundary.
I just had this issue. So there are a few approaches. The first is that new browsers support the
var formData = new FormData();
Follow this link to a blog with info about how support is limited to modern browsers but otherwise it totally solves this issue.
Otherwise you can post the form to an iframe using the target attribute.
When you post the form be sure to set the target to an iframe with its display property set to none.
The target is the name of the iframe. (Just so you know.)
I hope this helps
You could upload via $resource by assigning data to params attribute of resource actions like so:
$scope.uploadFile = function(files) {
var fdata = new FormData();
fdata.append("file", files[0]);
$resource('api/post/:id', { id: "#id" }, {
postWithFile: {
method: "POST",
data: fdata,
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}
}).postWithFile(fdata).$promise.then(function(response){
//successful
},function(error){
//error
});
};
I know this is a late entry but I have created a simple upload directive. Which you can get working in no time!
<input type="file" multiple ng-simple-upload web-api-url="/api/post"
callback-fn="myCallback" />
ng-simple-upload more on Github with an example using Web API.
I just wrote a simple directive (from existing one ofcourse) for a simple uploader in AngularJs.
(The exact jQuery uploader plugin is https://github.com/blueimp/jQuery-File-Upload)
A Simple Uploader using AngularJs (with CORS Implementation)
(Though the server side is for PHP, you can simple change it node also)

Resources