现在,我们在postgresql数据库中保存文件,并使用实体中的byte[]字段映射该内容。如果可以的话我需要调查
将内容数据直接从数据库流到HTTP输出流,并以相反的方式执行相同的操作,以便使用jpaBlob数据类型将二进制数据从HTTP流到数据库。我知道Blob有方法getBinaryStreamsetBinaryStream所以它可以工作,而且我们不需要将数据保存到内存中。
我关心的是数据库事务,因为我们正在将实体映射到DTO,第二件事是断开的Http请求,数据可能在某个时候丢失。
有没有人对这个解决方案有经验?

最佳答案

从blob读取数据流的解决方案:
现有的BLUB数据是通过将OutsStutts(由servlet容器提供)传递到事务方法的,该事务方法将实体BLUB数据从内部事务写入流。请注意,响应的内容类型是在写入数据之前设置的。
实体类:

public class Attachment {
   private java.sql.Blob data;
   public java.sql.Blob getData() { return data; }
}

服务方式:
@Transactional(readOnly = true)
public void copyContentsTo(long attachmentId, OutputStream outputStream) throws IOException {
  Attachment dbAttachment = attachmentRepository.findOne(attachmentId);

  try (InputStream is = dbAttachment.getData().getBinaryStream()) {
    IOUtils.copy(is, outputStream);

  } catch (SQLException e) {
    throw new ParameterException("Cannot extract BLOB for attachment #" + attachmentId, e);
  }
}

REST-API-Spring控制器方法:
@GetMapping(value = "/api/project-attachment/{attachment-id}/content")
@ResponseStatus(HttpStatus.OK)
public void getAttachmentContent(
    @PathVariable("attachment-id") long attachmentId,
    HttpServletResponse response,
    OutputStream stream) throws IOException {

    response.setContentType(getMime(attachmentId));
    attachmentService.copyContentsTo(attachmentId, stream);
}

关于spring - 将数据内容直接从数据库流传输到HTTP,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43912175/

10-09 00:36
查看更多