使用 JPA(REST) 将 BLOB 上传到数据库

Uploading BLOB to DB using JPA(REST)

我想从文件资源管理器上传 BLOB,但我对上传 blob 有点陌生,尤其是在使用 JPA(Java Persistance API) 时。

我想我会向您展示我的一些代码,看看您是否能给我任何关于正确方向的想法。

我的实体 class 看起来像这样:

@Entity
@Table(name = "exampletable")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Blob1337.findByTestBlob", query = "SELECT e FROM Blob1337 e WHERE e.testBlob = :testBlob")})

@Column(name = "test_blob")
private Integer testBlob;

public Integer getTestBlob() {
return testBlob;
}

public void setTestBlob(Integer testBlob) {
    this.testBlob = testBlob;
}

如您所见,我不确定这里的 BLOB 使用什么,所以现在是整数。

我的外观是这样的:

@PUT
@Path("{id}")
@Consumes({"application/json"})
public void edit(@PathParam("id") Integer id, Blob1337 entity) {

    Blob1337 entityToMerge = find(id);

    if (entity.getTestBlob() != null) {
        entityToMerge.setTestBlob(entity.getTestBlob());
}
    super.edit(entityToMerge);

}

如何让外观和实体 class 知道这是一个 BLOB?我希望能够通过 ajax post 上传此文档,如果我是正确的话,这应该是非常初级的。

谢谢!非常感谢任何帮助!

我终于成功通过 rest/ajax

上传了一个 blob

Facade 应该看起来像这样(这需要一个 blob 并将其流式传输到数据库中):

    @POST
    @Path("upload/{id}")
    @Consumes({"application/x-www-form-urlencoded", "multipart/form-data"})

    public void addBlob(@PathParam("id") Integer id, @FormDataParam("file") InputStream uploadedInputStream) throws IOException {
        E24ClientTemp entityToMerge = find(id);
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int read = 0;
            byte[] bytes = new byte[1024];
            while ((read = uploadedInputStream.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            entityToMerge.setTestBlob(out.toByteArray());
            super.edit(entityToMerge);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

而不是上面问题中发布的 blob integer,我使用了 byte[]@Lob 注释

像这样:

@Lob
@Column(name = "test_blob")
private byte[] testBlob;

奖金,对于未来的访问者 - 这是 Ajax 在这种情况下的样子的示例:

    $(".uploadDocumentGeneral").on("click", function (evt) {
    IdToEdit = $(this).closest('tr').siblings().find('p.important').text();
    var url = "http://localhost:10110/MavenProject/api123/General123/upload/"+IdToEdit;
    evt.preventDefault();

    var documentData = new FormData();
    documentData.append('file', $('input#file.findDocumentOnboarding')[0].files[0]);
    $.ajax({
        url: url,
        type: 'POST',
        data: documentData,
        cache: false,
        contentType: false,
        processData: false,
        success: function (response) {
            alert("Document uploaded successfully.");
        }
    });

    return false;
});