Post upload files in angular 4 from spring boot?

Viewed 2161

I have an api handle the request to upload file (in spring boot) as follows:

@PostMapping("/api/admin/product/{id}/upload")
public ResponseEntity<Product> postUpload(@PathVariable("id") Integer id, @RequestParam("image") MultipartFile imageFile) {
    Product product = productService.findOne(id);
    return new ResponseEntity<>(productService.upload(product, imageFile),HttpStatus.OK);
}

Below is a service to process my requests. How should I fix it to fit the above api?

@Injectable()
export class ProductServiceService {
  private baseUrl = 'http://localhost:8080/api/admin/product';
  private headers = new Headers({'Content-Type' : 'multipart/form-data', 'Access-Control-Allow-Origin' : '*'});
  private options = new RequestOptions({headers: this.headers});
  constructor(private _http: Http) { }
  postUpload(id) {
    const formdata: FormData = new FormData();
formdata.append('image', image);
return this._http.post(this.baseUrl + '/' + id + '/upload', formdata, this.options)
            .map((res: Response) => res.json())
            .catch(this.errorHandler);
  }
  errorHandler(error: Response) {
    return Observable.throw(error || 'SERVER ERROR');
  }
}
And this is the error after build enter image description here Thanks!

1 Answers

Few of my observations based on the code shared by you:

  • private headers = new Headers({'Content-Type' : 'application/json'});. This is wrong, Content type should be multipart/form-data
  • this._http.get - this should be POST
  • File should be associated by image request param

I am not familiar with Angular to give you an exact answer.

Update:

If your client application is another Spring Boot application then you can run Zuul proxy on your Angular JS app and map /api URL to http://localhost:8080/api. Enabling Zuul Proxy is as simple as * Adding dependency on spring-cloud-starter-zuul in your pom * annotating the configuration class with @EnableZuulProxy * Adding following in the properties: zuul.routes.api.url http://localhost:8080/api

So from your client app you call the api: http://localhost:4200/api/admin/product/17/upload and your client app (using Zuul proxy) will invoke the http://localhost:8080/api/admin/product/17/upload at the server.

Related