I have created a webpage (JSP & AngularJS) that contains a form allowing the user to attach a file and send it to the server (Java Servlet). The server will then take that file and forward it to an API by attaching it to a HTTP POST request.
The code I have at the moment within the JSP File and the AngularJS Controller appears to be working correctly. Once the file is sent from the webpage to the server, I can then access some of the file details (field name and size but not content type or file name) in the Java Servlet and print them out via System.out.println()
.
The problem I am facing at the moment is trying to find a way how to attach the FileItem (attachment) to the HttpPost (postRequest).
I have read a number of examples online on how files are uploaded, however these examples always assume the file will be stored on a disk on the server instead of being forwarded elsewhere.
This is my current code (the problem seems to be in the Java Servlet section):
JSP File:
<form name="issueForm">
<input id="attachment" class="form-control" type="file" data-ng-model="attachment"/>
<button type="submit" data-ng-click="setAttachment()">Create Issue</button>
</form>
AngularJS Controller:
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]);
});
});
}
};
}]);
$scope.setAttachment = function()
{
var attachment = $scope.attachment;
var fd = new FormData();
fd.append('attachment', attachment);
$http({
url: 'IssueAttachment',
method: 'POST',
transformRequest: function(data, headersGetterFunction) { return data; },
headers: { 'Content-Type': undefined },
data: fd
})
.success(function(data, status) { alert("Success: " + status); })
.error(function(data, status) { alert("Error: " + status); });
}
Java Servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
FileItem attachment = null;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) { System.out.println("Not Multipart Content!"); }
else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(new ServletRequestContext(request));
} catch (FileUploadException e) { e.printStackTrace(); }
try {
//Get attachment and print details
//This section prints "attachment", 9, null, null in that order).
attachment = (FileItem) items.get(0);
System.out.println("Field Name: " + attachment.getFieldName());
System.out.println("Size: " + attachment.getSize());
System.out.println("Content Type: " + attachment.getContentType());
System.out.println("File Name: " + attachment.getName());
} catch (Exception e) { e.printStackTrace(); }
//Create a HTTP POST and send the attachment.
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost(API_URL);
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.addPart("attachment", new FileBody(attachment)); //THE ERROR OCCURS HERE.
postRequest.setEntity(entity.build());
try {
HttpResponse response = httpClient.execute(postRequest);
} catch (IOException e) { e.printStackTrace(); }
}
}