2017-08-16 76 views
0

我想先说说我已经搜索了很高和低的工作,并在这里工作了整整一天,8小时,然后才诉诸问题。在大多数例子中,我看到没有人看到端点api的样子,所以我可以看到api的期望,所以我会同时显示前端和后端。Angular 2将文件上传到Java Api

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... 
} 

现在在我的角2的代码,我不知道如何发送它,我已经试过很多东西太多在这个问题覆盖,所以我会后我最亲近的尝试。我有一个调用服务,使得这里的呼叫的组件是服务功能

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

} 

现在,当我尝试这个,我得到回应400 - 错误的请求。有没有人看到我可能会失踪或有一个想法什么修复。

我已经看到了这些链接,并没有能够把它一起

  1. File Upload with Angular 2 to rest api
  2. Angular post uploaded file
+0

可能是你已经尝试过这一点,但无论如何,我会建议您单独测试后端代码通过一些其他客户端(例如邮差),并确保后台运行良好。然后,如果它无法尝试交叉由前端执行的http请求,并将它们与之前使用的有效http请求进行比较。交集的东西也可以通过邮差完成。 –

+0

我认为你的意思是拦截,而不是交集。 – AndreyS

+0

@AndreyS你是对的,谢谢。但我不能再改变评论 –

回答

1

于是我找到了解决我的问题

我删除来自我的要求,它的工作。我不知道为什么,因为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)); 
}