[英]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.