[英]Angular 2 Upload File to Java Api
I want to start this off by saying I have searched high and low and worked on this for a full day, 8hrs, before resorting to asking a question. 首先,我想说一下我已经搜索了很多东西,然后花了整整8个小时的时间进行研究,然后才提出问题。 In most of the examples I saw no one shows what the endpoint api looks like so I could see what the api was expecting so I will show both, the front and backend.
在大多数示例中,我都看不到端点api的外观,因此我可以看到api的预期,因此我将同时显示前端和后端。
myJavaRootResource.java myJavaRootResource.java
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@Path("/import/{id}")
public Response import(@FormDataParam("file") InputStream fileInputStream, @Context ServletContext application,
@Context HttpServletRequest request, @Context UriInfo info, @PathParam("id") Integer id) {
System.out.println("*** MADE it ***");
...blah blah...
}
Now in my Angular 2 code I have no idea how to send it, I have tried lots of things too many to cover in this question so I will post my closest attempt. 现在,在我的Angular 2代码中,我不知道如何发送它,我已经尝试了很多太多的东西来解决这个问题,所以我将发布最接近的尝试。 I have a component that calls a service that makes the call here is that service function
我有一个调用服务的组件,在这里进行调用的是该服务功能
my.service.ts 我的服务
importIt(id: number, myFile: File) {
const dataUrl = 'the/path/import/' + id;
const formData = new FormData();
formData.append('file', myFile);
const headers = new Headers({'Content-Type': 'multipart/form-data'});
let options = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
});
return this.http.post(dataUrl, formData, options)
.map(res => res)
.catch(this.handleError.bind(this));
}
Now when I try this I get a response 400 - Bad Request. 现在,当我尝试此操作时,我会收到响应400-错误的请求。 Does anyone see what I might be missing or have an idea what to fix.
有谁看到我可能会丢失的东西,或者有什么解决办法的想法。
I have seen these links and haven't been able to put it together 我看过这些链接,但无法将它们放在一起
So I found a solution to my problem 所以我找到了解决问题的办法
I removed the headers from my request and it worked. 我从请求中删除了标头,它起作用了。 I have no idea why, because the api is looking for those headers.
我不知道为什么,因为api正在寻找这些标头。
my.service.ts 我的服务
importIt(id: number, myFile: File) {
const dataUrl = 'the/path/import/' + id;
const formData = new FormData();
formData.append('file', myFile);
let options = new RequestOptions({
method: RequestMethod.Post
});
return this.http.post(dataUrl, formData, options)
.map(res => res)
.catch(this.handleError.bind(this));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.