user962206
user962206

Reputation: 16147

Spring Boot MVC How to send a file to browser/user

my entity looks like this:

@Entity
@Table(name = "ATTACHMENT")
public class Attachment extends JpaModel{

    @Column(name="FILE")
    private byte[] file;

    public byte[] getFile() {
        return file;
    }

    public void setFile(byte[] file) {
        this.file = file;
    }

    // Other properties and setters and getters
}

However, it's in my bytes how would tell my Spring controller to return this as a file?

Regards

Upvotes: 3

Views: 2425

Answers (1)

Bohuslav Burghardt
Bohuslav Burghardt

Reputation: 34796

This should work:

@RequestMapping("/attachment")
public ResponseEntity<byte[]> getAttachment() throws IOException {
    Attachment attachment = null; // Retrieve your attachment somehow
    return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN).body(attachment.getFile());
}

or you can use this:

@ResponseBody
@RequestMapping("/attachment", produces={ /* Types of files */ })
public byte[] getAttachment() {
    Attachment attachment = null; // Retrieve your attachment somehow
    return attachment.getFile();
}

Using the second approach you must set the possible types of the attachment in the produces param of @RequestMapping. The client will then have to request content type in the Accept header.

The first example allows you to set content type based on your attachment (I assume that you will have it stored in the DB somehow along with the content), which is probably what you need.

Upvotes: 3

Related Questions