如何将FileItem附加到HTTP POST请求?

时间:2016-12-15 00:42:10

标签: java angularjs jsp servlets upload

我创建了一个网页(JSP& AngularJS),其中包含一个允许用户附加文件并将其发送到服务器(Java Servlet)的表单。然后,服务器将获取该文件,并通过将其附加到HTTP POST请求将其转发到API。

我目前在JSP文件和AngularJS控制器中的代码似乎正常工作。一旦文件从网页发送到服务器,我就可以访问Java Servlet中的一些文件详细信息(字段名称和大小,但不是内容类型或文件名),并通过System.out.println()打印出来。 / p>

我目前面临的问题是试图找到一种方法将FileItem(附件)附加到HttpPost(postRequest)。

我已经在线阅读了一些关于如何上传文件的例子,但是这些例子总是假设文件将存储在服务器上的磁盘上,而不是转发到其他地方。

这是我当前的代码(问题似乎出现在Java Servlet部分中):

JSP文件:

<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控制器:

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(); }
}
}

1 个答案:

答案 0 :(得分:1)

使用以下内容结束:

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();