1

Image

I want to write a client code to consume an API. The API is expecting a text file. When I select the binary file option in the postman tool and select any text file from my local it worked. how to implement this in spring ?. I have tried MULTIPART_FORM_DATA but no luck.

1
  • Show your efforts Commented Jul 8, 2021 at 6:03

1 Answer 1

0

If You mean file

@RestController
public class FileContentController {
    
@RequestMapping(value="/up", method = RequestMethod.POST)
public ResponseEntity<?> upload(@RequestParam("file") MultipartFile file) 
        throws IOException {
        String  contentType=file.getContentType());
        InputStream i=file.getInputStream();
        return new ResponseEntity<>(HttpStatus.OK);
    }
    return null;
}

also spring boot has multi part confs, you should enable it and set size and tempdir ,In Earlier version spring boot need to add:

spring.servlet.multipart.max-file-size=128KB
spring.servlet.multipart.max-request-size=128KB
spring.servlet.multipart.enabled=true
spring.servlet.multipart.location=${java.io.tmpdir}

However in your client code you should not set content-type application/json in your header post request simple fetch should be such

const input = document.getElementById('uploadInput');
const data = new FormData();
data.append('file', input.files[0]);
var resp = await fetch('upload/', {
                        method: 'POST',
                        body: data
                          });
if (!resp.ok) {
  throw new Error(`HTTP error! status: ${resp.status}`);
}
if (resp.ok) {
  await this.images();
}
   
Sign up to request clarification or add additional context in comments.

Comments

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.