如何使用Java Spring Boot从MySQL检索并展示已上传的PDF文件
Spring Boot 检索并展示MySQL中存储的PDF文件问题解决
先修正你的实体类问题
你的DBFile实体类存在语法错误,这可能是后续检索异常的根源:
- 变量名不符合Java命名规范(包含空格):
file Type→fileType,submission Date→submissionDate - 构造函数名错误:
DB File→DBFile - 构造函数中
this.id = ID;无意义(ID未定义,且id为自动生成字段,无需手动赋值) - 构造函数未闭合,缺少无参构造函数(JPA强制要求)
修正后的实体类代码:
@Entity @Table(name = "permission") public class DBFile { @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid2") private String id; private String filename; private String fileType; private String name; private Date submissionDate = new java.util.Date(); @Lob private byte[] data; // 业务构造函数 public DBFile(String filename, String fileType, byte[] data, String name) { super(); this.filename = filename; this.fileType = fileType; this.data = data; this.name = name; } // JPA要求的无参构造函数 public DBFile() { super(); } // 生成所有字段的getter和setter方法 public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public String getFileType() { return fileType; } public void setFileType(String fileType) { this.fileType = fileType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getSubmissionDate() { return submissionDate; } public void setSubmissionDate(Date submissionDate) { this.submissionDate = submissionDate; } public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } }
实现PDF检索与展示的Controller
要在浏览器中直接展示PDF,需将数据库存储的byte[]数据以正确的响应头输出,让浏览器识别为PDF文件:
@RestController @RequestMapping("/api/files") public class FileController { @Autowired private DBFileRepository dbFileRepository; // 需自定义继承JpaRepository的接口 @GetMapping("/view/{fileId}") public void viewPdf(@PathVariable String fileId, HttpServletResponse response) throws IOException { DBFile dbFile = dbFileRepository.findById(fileId) .orElseThrow(() -> new RuntimeException("目标文件不存在")); // 设置响应头,指定文件类型和展示方式 response.setContentType(dbFile.getFileType()); // inline表示在浏览器内打开,改为attachment则触发下载 response.setHeader("Content-Disposition", "inline; filename=\"" + dbFile.getFilename() + "\""); response.setContentLength(dbFile.getData().length); // 将字节数据写入响应流 try (OutputStream os = response.getOutputStream()) { os.write(dbFile.getData()); os.flush(); } } }
关键注意事项
- 确保
DBFileRepository继承JpaRepository<DBFile, String>,实现基础CRUD操作 - 若PDF文件过大,建议采用流式读取(避免一次性加载
byte[]导致内存溢出) - 上传时需保证PDF字节数据完整存储,避免截断
- 测试时直接访问
/api/files/view/{你的文件ID}即可在浏览器中查看PDF
内容的提问来源于stack exchange,提问作者saren vs
相关产品推荐
相关产品推荐

