从数据库下载文件而不将其保存在服务器上

Ama*_*man 0 java pdf jersey spring-mybatis spring-jersey

我想使用 jersey api 从数据库中检索 pdf(存储为 BLOB)我使用 mybatis 作为数据库框架。我可以下载 pdf,但问题是我将输入流作为数据库获取,我将其另存为文件,然后在响应中传递它,但我不想将该文件保存在服务器中,我希望文件直接到下载给用户。

当前流程:

数据库----->输入流----->文件----------->添加到响应----->用户下载它

         retrieving        making file  passing file          user downloads
Run Code Online (Sandbox Code Playgroud)

我想要的是 :

DATABASE--------->输入流------------>添加到响应------->用户下载它

         retrieving         passing file              user downloads
Run Code Online (Sandbox Code Playgroud)

我想删除服务器中的文件制作,因为数据是机密的

资源接口

@GET
@Path("v1/download/{id}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadFile(@PathParam("id") int id) throws IOException, SQLException;
Run Code Online (Sandbox Code Playgroud)

资源实施

@Override
public Response downloadFile(int id) throws IOException, SQLException {
    // TODO Auto-generated method stub
    File file = fileUploadService.downloadFile(id);

    ResponseBuilder response = Response.ok(file);
    response.header("Content-Disposition", "attachment;filename=aman.pdf");
    return response.build();
}
Run Code Online (Sandbox Code Playgroud)

服务方式

@Override
public File downloadFile(int id) throws IOException {
    // TODO Auto-generated method stub
    File fil=new File("src/main/resources/Sample.pdf");
    FileUploadModel fm =mapper.downloadFile(id);
    InputStream inputStream = fm.getDaFile();
    outputStream = new FileOutputStream(fil);
    int read = 0;
    byte[] bytes = new byte[102400000];

    while ((read = inputStream.read(bytes)) != -1) {
        outputStream.write(bytes, 0, read);
    }
    return fil;
}
Run Code Online (Sandbox Code Playgroud)

此代码正在工作,但我想删除服务器端的文件制作,即我想删除File fil=new File("src/main/resources/Sample.pdf"),此操作在服务方法中。

提前致谢。

Mik*_*ike 5

不要使用 File,而是使用 ByteArrayOutputStream 并写入它。然后将结果作为 byte[] 返回,您可以将其传递给您的 Response.ok(content)。

没有测试这个,但像这样:

public byte[] downloadFile(int id) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    FileUploadModel fm =mapper.downloadFile(id);
    InputStream inputStream = fm.getDaFile();
    int read = 0;
    byte[] bytes = new byte[1024];

    while ((read = inputStream.read(bytes)) != -1) {
        out.write(bytes, 0, read);
    }
    return out.toByteArray();
}
Run Code Online (Sandbox Code Playgroud)

此外,要分配给数组的字节很多。您可以尝试适合您的方法,但 1024 之类的可能完全足够。

您可能还想为 Content-Type 的响应添加另一个标头。