1

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(); }
}
}
dat3450
  • 954
  • 3
  • 13
  • 27
  • *//THE ERROR OCCURS HERE.* **Care to share?** – Scary Wombat Dec 15 '16 at 00:45
  • *but not content type or file name* **maybe this is telling you something?** – Scary Wombat Dec 15 '16 at 00:48
  • If the **attachment** variable were a File type then the line `entity.addPart("attachment", new FileBody(attachment));` would run, however it is instead a FileItem so Eclipse comes up with an error and underlines it. I cannot use File type as I do not want to store it on disk but forward it. – dat3450 Dec 15 '16 at 00:49
  • Does this help? https://gist.github.com/Arinerron/1fc812f62d4679c70eae85682ff4607d – Aaron Esau Dec 15 '16 at 00:51
  • @Arin, unfortunately that can't be used as `FileBody(file, "image/jpeg");` is expecting **file** to be a File type instead of a FileItem type which is what I have at the moment. – dat3450 Dec 15 '16 at 00:56
  • @dat3450 Okay. Well, if you can't find a solution, there's always this: http://stackoverflow.com/questions/15072917/convert-fileitem-to-file – Aaron Esau Dec 15 '16 at 00:58
  • @Arin, yeah I'm familiar with that but it would store the file on the server disk, which is not required. – dat3450 Dec 15 '16 at 01:00

1 Answers1

1

Ended up using the following:

FileItem file = (FileItem)items.get(0);
//Create a temporary file.
File myFile = File.createTempFile(base, extension);
//Write contents to temporary file.
file.write(myFile);

/**
* Do whatever you want with the temporary file here...
*/

//Delete the temporary file.
myFile.delete(); //-OR- myFile.deleteOnExit();
dat3450
  • 954
  • 3
  • 13
  • 27