【问题标题】:How to attach a FileItem to a HTTP POST request?如何将 FileItem 附加到 HTTP POST 请求?
【发布时间】:2017-04-30 11:48:34
【问题描述】:

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

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

我目前面临的问题是试图找到一种方法如何将 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(); }
}
}

【问题讨论】:

  • //此处出现错误。 愿意分享吗?
  • 但不是内容类型或文件名 这可能告诉你什么?
  • 如果 attachment 变量是 File 类型,那么 entity.addPart("attachment", new FileBody(attachment)); 行会运行,但它是 FileItem,因此 Eclipse 会出现错误并在其下划线。我不能使用文件类型,因为我不想将它存储在磁盘上而是转发它。
  • @Arin,不幸的是不能用作 FileBody(file, "image/jpeg"); 期望 file 是 File 类型而不是 FileItem 类型,这是我目前所拥有的.

标签: java angularjs jsp servlets upload


【解决方案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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多