代码之家  ›  专栏  ›  技术社区  ›  Aman

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

  •  0
  • Aman  · 技术社区  · 7 年前

    我想使用jersey api从数据库中检索pdf(存储为BLOB) 我可以下载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;
    }
    

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

    1 回复  |  直到 7 年前
        1
  •  5
  •   Mike    7 年前

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

    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个可能就足够了。