siva prakash
siva prakash

Reputation: 11

Rest API returning byte[] i response

What should be in the consumes and produces for Rest API which is returning byte[] of file in the response. No file params are included in the request .

Upvotes: 0

Views: 2990

Answers (3)

Vikram Singh Shekhawat
Vikram Singh Shekhawat

Reputation: 762

You should set the media type on basis of file content type.

for example:

  @GetMapping
  public HttpEntity returnByteArray() {
      String filepath = ; //filepath
      String contentType = FileTypeMap.getDefaultFileTypeMap().getContentType(filePath);
      byte[] byteContent = ; //Content
      final HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.valueOf(contentType));
      return new HttpEntity(byteContent, headers);
}

OR

If you always return the same content file type then you can also set in

    @GetMapping(produces = "mime_type")
    public byte[] returnByteArray() {
      return new byte[0];
    }

Upvotes: 0

shihabudheenk
shihabudheenk

Reputation: 636

You could use the below for returning byte[]

@Produces(MediaType.APPLICATION_OCTET_STREAM)

Upvotes: 1

Rajvir
Rajvir

Reputation: 108

You can use 'MultipartFile' for the purpose of consuming and sending back a file in response.

You can have a look at the following tutorial at spring.io for detailed tutorial: https://spring.io/guides/gs/uploading-files/

Hope it helps!

Upvotes: 0

Related Questions