繁体   English   中英

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

[英]Download the file from database without saving it on server

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

当前流程:

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

         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;
}

这段代码有效,但是我想删除服务器端的文件,即我想要删除File fil = new File(“ src / main / resources / Sample.pdf”) ,此操作在service方法中。

提前致谢。

代替使用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();
}

另外,要分配给数组的字节很多。 您可以尝试最适合自己的方法,但是像1024这样的条件就足够了。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM