简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM