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

How to attach a FileItem to a HTTP POST request?

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

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

我目前面临的问题是试图找到一种方法将 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 小服务程序:

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

最终使用了以下内容:

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