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();
}