0

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

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

  1. File Upload with Angular 2 to rest api
  2. Angular post uploaded file
Kyle Krzeski
  • 6,183
  • 6
  • 41
  • 52
Logan H
  • 3,383
  • 2
  • 33
  • 50
  • May be you already tried this but anyway I would suggest you to test your backend code separately via some rest client (e.g. Postman) and make sure the backend works well. Then if it does not help try to intersect http requests performed by the frontend and compare them with valid http request that you used before. Intersection stuff could also be done via Postman. – Sasha Shpota Aug 16 '17 at 16:58
  • I think you meant interception, not intersection. – Andrey Saleba Aug 16 '17 at 17:45
  • @AndreyS you're right, thanks. But I can't change comment anymore – Sasha Shpota Aug 16 '17 at 18:17

1 Answers1

2

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.

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));
}
Logan H
  • 3,383
  • 2
  • 33
  • 50