gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:59:38 24 4
gpt4 key购买 nike

我创建了一个网页(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com