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

Java 从数据库下载文件而不将其保存在服务器上,java,pdf,jersey,spring-mybatis,spring-jersey,Java,Pdf,Jersey,Spring Mybatis,Spring Jersey,我想使用jersey api从数据库中检索pdf(存储为BLOB) 我使用mybatis作为数据库框架。 我可以下载pdf,但问题是我将输入流作为数据库保存为文件,然后将其作为响应传递给用户,但我不想将该文件保存在服务器中,我希望将该文件直接下载给用户 当前流程: 数据库------->输入流------->文件------->添加到响应------->用户下载它 retrieving making file passing file user

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

当前流程:

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

         retrieving        making file  passing file          user downloads
我想要的是:

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

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

资源接口

@GET
@Path("v1/download/{id}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadFile(@PathParam("id") int id) throws IOException, SQLException;
资源整合

@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();
}
服务方式

@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;
}
此代码正在工作,但我想删除服务器端的文件制作,即我想删除文件fil=new文件(“src/main/resources/Sample.pdf”),此操作正在使用中


提前感谢。

使用ByteArrayOutputStream并写入文件,而不是使用文件。然后将结果作为字节[]返回,您可以将其传递给响应。ok(内容)

没有对此进行测试,但类似这样的测试:

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();
}
另外,分配给数组的字节也很多。你可以尝试对你有用的东西,但是像1024这样的东西可能就足够了


您可能还需要为内容类型的响应添加另一个标题。

使用ByteArrayOutputStream并写入,而不是使用File。然后将结果作为字节[]返回,您可以将其传递给响应。ok(内容)

没有对此进行测试,但类似这样的测试:

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();
}
另外,分配给数组的字节也很多。你可以尝试对你有用的东西,但是像1024这样的东西可能就足够了

您可能还需要为内容类型的响应添加另一个标题