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

原文 标签 java angularjs jsp servlets upload

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

我目前在 JSP 文件和 AngularJS Controller 中的代码似乎工作正常。一旦文件从网页发送到服务器,我就可以访问 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 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(); }
}
}

最佳答案

最终使用以下内容:

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

关于java - 如何将 FileItem 附加到 HTTP POST 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41154609/

相关文章:

java - 谷歌地图 - 我正在尝试更新当前位置,但我的应用程序一打开它就关闭了。这是代码-

来自字符串的 Java 星期几

javascript - 根据外部ng-repeat索引过滤内部ng-repeat

javascript - 保存AngularJS后如何在页面上显示新数据

java - 在一个 JPG 文件中导出多个图像

java - Spring MVC 页面

java - 日期时间不显示

java - SoundPoolThread 通过 JNI ERROR "accessed deleted global reference"导致 SIGSEGV

javascript - ng-init 预选的选项在 ngOptions | 中不起作用AngularJS

java - #{facesContext} EL 表达式未在运行时解析