2

I want to upload a file from Angular to Spring. I tried this:

@PostMapping(path = "/upload", produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> uploadData(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) throws Exception {

    ......
    return new ResponseEntity<>(originalName, HttpStatus.OK);
}

Angular code:

const formData = new FormData();
formData.append('file', file, file.name);
return this.http.post(environment.api.urls.merchants.uploadLogo, formData);

But I get error:

message: "Unexpected token S in JSON at position 0"
stack: "SyntaxError: Unexpected token S in JSON at position 0↵    at JSON.parse (<

I suppose that Spring has to return JSON response, but for some reason it's not working.

Do you know how I have to configure the Spring endpoint properly?

EDIT I tried this:

@PostMapping(path = "/upload", produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<String> uploadData(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) throws Exception {
    ......
    return new ResponseEntity<>(originalName, HttpStatus.OK);
}
Lemmy
  • 2,437
  • 1
  • 22
  • 30
Peter Penzov
  • 1,126
  • 134
  • 430
  • 808

1 Answers1

3

Your endpoint should produces="text/plain" because you are returning String not a json object. Angular on the other hand is expecting json and therefore you are getting that kind of message.

If you want to return json, create wrapper around that string message.

EDIT: Please take a look at this to see example Spring MVC - How to return simple String as JSON in Rest Controller

Lemmy
  • 2,437
  • 1
  • 22
  • 30
  • I tried again to use @PostMapping(path = "/upload", produces = {MediaType.APPLICATION_JSON_VALUE}) but it's not working. Any idea why? – Peter Penzov Aug 11 '19 at 20:21
  • Because you didn’t change anything. Did you create StringResponse object like this: public class StringResponse { private String response; public StringResponse(String s) { this.response = s; } // get/set omitted... } and then return ResponseEntity – Lemmy Aug 11 '19 at 20:26
  • No, I would like to avoid if it's possible – Peter Penzov Aug 11 '19 at 20:28
  • Ok, then change this MediaType.APPLICATION_JSON_VALUE to MediaType.TEXT_PLAIN because you what to return String, not a json. You must tell Angular what will be return so it can use it. – Lemmy Aug 11 '19 at 20:33
  • Your endpoint should looks like @PostMapping(path = "/upload", produces = {MediaType.TEXT_PLAIN) – Lemmy Aug 11 '19 at 20:35
  • And how do you think String "some string" will be represent as json? If you don't have key: value pair? – Lemmy Aug 11 '19 at 20:42