I am currently facing a challenge in developing a webpage that enables file uploads from a local machine to a server using AngularJS and Java Servlet. My approach involves sending data to the server using $http.post and attempting to read the file data using apache commons-fileupload. However, I have encountered an issue where the file data is not sent in the expected multipart/form-data format, preventing commons-fileupload from properly detecting the file data on the server side. Manually setting {headers:{'Content-Type':'multipart/form-data'}} in the post request results in an exception being thrown.
Below is the HTML page and JS file I am utilizing:
HTML Page:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="js/upload.js"></script>
<head>
<title>Admin</title>
</head>
<body ng-app="uploadApp" ng-controller="UploadCtrl">
<form name="upload" class="form" data-ng-submit="addFile()">
<p>Please specify a file, or a set of files:<br>
<input type="file" name="file" onchange="angular.element(this).scope().attachedFile(this)" /></p>
<button type="submit">Upload</button>
</form>
</body>
</html>
JS file:
var app=angular.module('uploadApp',[]);
app.controller('UploadCtrl', ['$scope','$http',function($scope,$http) {
$scope.attachedFile = function(element) {
$scope.$apply(function($scope) {
$scope.file = element.files[0];
});
console.log('file attached');
};
$scope.addFile = function() {
var url = '/upload';
var fd = new FormData();
fd.append("file",$scope.file);
$http.post(url, fd)
.success(function(data, status, headers, config) {
console.log('success');
})
.error(function(data, status, headers, config) {
console.log('error');
})
};
}])
In examining the issue, I observed the data received on the server side in the following format:
------WebKitFormBoundaryXXXXXXXXXXXXX
Content-Disposition: form-data; name="file"; filename="XXX.txt"
Content-Type: text/plain
filedata
------WebKitFormBoundaryXXXXXXXXXXXXX--
The problem lies in the generated FormData not specifying Content-Type: multipart/form-data, defaulting instead based on the file extension, thus causing issues with commons-fileupload on the server side.
I am seeking advice on a possible solution to this issue. Is there a way to manually set the content type to multipart/form-data in the FormData/request created, or is there an alternative method/library to parse the received data on the server side?