Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring Boot MVC如何向浏览器/用户发送文件_Java_Spring_Spring Mvc_Spring Boot - Fatal编程技术网

Java Spring Boot MVC如何向浏览器/用户发送文件

Java Spring Boot MVC如何向浏览器/用户发送文件,java,spring,spring-mvc,spring-boot,Java,Spring,Spring Mvc,Spring Boot,我的实体如下所示: @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.

我的实体如下所示:

@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
}
然而,它在我的字节中,如何告诉我的Spring控制器将其作为文件返回

关于

这应该是可行的:

@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());
}
使用第二种方法,您必须在
@RequestMapping
products
参数中设置附件的可能类型。然后,客户端必须在
Accept
标题中请求内容类型


第一个示例允许您根据附件设置内容类型(我假设您将以某种方式将其与内容一起存储在DB中),这可能是您所需要的。

好的,如果将第一个版本编写为
return ResponseEntity.ok().contentType(MediaType.TEXT\u PLAIN).body,那么它的可读性会更好(attachment.getFile());
@zeroflagL很好,谢谢你的提示。我已经更新了答案。
@ResponseBody
@RequestMapping("/attachment", produces={ /* Types of files */ })
public byte[] getAttachment() {
    Attachment attachment = null; // Retrieve your attachment somehow
    return attachment.getFile();
}