1

I need to upload files using angular and spring boot.

Angular service:

 const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json;multi-part/form-data'})
    };

addProduct(productRequest: ProductRequest, creator: string, tradeReference: string, selectedImage: File) {

    const trimCreator = creator.trim();
    const trimTradeReference = tradeReference.trim();   

    const formData =  new FormData();
    formData.append('images', selectedImage);


    return this.http.post<any>(baseUrl + '/addProduct', {formData, productRequest, trimCreator, trimTradeReference} , httpOptions)
      .pipe(
        catchError(this.handleError)
      );
  }

and my backend Rest service is the following:

    @ApiOperation(value = "add product", response = Iterable.class)
    @ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully added product") })
    @PostMapping("/addProduct")
    public void addProduct(@RequestPart(value = "images") MultipartFile[] images,
                            @RequestPart(value = "product") Product product,
                            @RequestPart(value = "creator") @ApiParam(value = "creator") String creator,
                            @RequestPart(value = "tradeReference") @ApiParam(value = "tradeReference") String tradeReference
                            ) throws Exception {

        Arrays.asList(images)
                .stream()
                .forEach(image -> uploadImages(image, product));
        traderServices.addProduct(product, creator, tradeReference);
    }

The error:

{"timestamp":"2020-04-23T13:35:03.114+0000","status":500,"error":"Internal Server Error","message":"Current request is not a multipart request","trace":"org.springframework.web.multipart.MultipartException: Current request is not a multipart request\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestPartMethodArgumentResolver.resolveArgument(RequestPartMethodArgumentResolver.java:158)\r\n\tat ,"path":"/api/trader/addProduct"}

I tried to update PostMapping like

@PostMapping(value = "/'addProduct", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_JSON_VALUE})

also I deleted consumes information and header informations in angular service, but it doesn't work.

With postman, it works fine.

enter image description here

So can't understand why it doesn't work!

Thanks

1 Answer 1

3

Solution:

//Angular service:

const options = {} as any;

addProduct(productRequest: ProductRequest, selectedImages: File[]) {

        const formData =  new FormData();        

        for (let i = 0; i < selectedImages.length; i++) {
          formData.append('images', selectedImages[i]);
        }

        Object.keys(productRequest).forEach((key) => {formData.append(key, productRequest[key]); });

        return this.http.post<any>(baseUrl + '/addProduct', formData , options)
          .pipe(
            catchError(this.handleError)
          );
      }

//Spring REST Service:

 @ApiOperation(value = "add product", response = Iterable.class)
    @ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully added product") })
    @PostMapping("/addProduct")
    public void addProduct(@RequestPart(value = "images")       @ApiParam(value = "images")  MultipartFile[] images,
                           @RequestPart(value = "productName")  @ApiParam(value = "productName")  String productName,
                           @RequestPart(value = "description")  @ApiParam(value = "description")  String description,
                           @RequestPart(value = "realPrice")    @ApiParam(value = "realPrice")    String realPrice,
                           @RequestPart(value = "category")     @ApiParam(value = "category")     String category,
                           @RequestPart(value = "creator")      @ApiParam(value = "creator")      String creator,
                           @RequestPart(value = "tradeReference") @ApiParam(value = "tradeReference") String tradeReference
                 ) throws Exception {

        Product p = createProduct(productName, description, Double.valueOf(realPrice), category, creator, tradeReference);
        Arrays.asList(images)
                .stream()
                .forEach(image -> uploadImages(image, p));
        traderServices.addProduct(p);
    }

note that Product object is splitted into parameters to avoid errors like "Content type 'application/octet-stream' not supported" and "Content type 'multipart/form-data' not supported". Changing 'realPrice' parameter type to Double, generate an exception of type "Content type 'application/octet-stream' not supported", it works with Strings.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. It worked for me and also learnt the solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.