JAVA从数据库读取BLOB下载

作妖的程序员 2020-09-15 06:03:44
@Path("/download")
@POST
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response download(@FormParam("tid") String tid) {
List<NdsbQyjbxxDTO> list = ndsbBLOImpl.queryFileById(tid);
NdsbQyjbxxDTO dto = list.get(0);
String fjmc = dto.getFjmc();//附件名称
byte fjnr[] = dto.getFjnr();//附件内容
ResponseBuilder builder = Response.ok(fjnr, "application/x-download;charset=utf-8");
try {
builder.header("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fjmc, "UTF-8") + "");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Response response =builder.build();
return response;
}

下载的文件一直是1KB,打开显示如下:
...全文
2137 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
KeepSayingNo 2020-09-16
  • 打赏
  • 举报
回复
你要把你的文件写道这个对象里面,然后再返回吧 ByteArrayOutputStream outStream =new ByteArrayOutputStream();
qybao 2020-09-15
  • 打赏
  • 举报
回复
你从数据库读出的是byte数组,应该用stream的形式来返回
@Path("/download")
@POST
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response download(@FormParam("tid") String tid) {
List<NdsbQyjbxxDTO> list = ndsbBLOImpl.queryFileById(tid);
NdsbQyjbxxDTO dto = list.get(0);
String fjmc = dto.getFjmc();//附件名称
byte fjnr[] = dto.getFjnr();//附件内容
StreamingOutput stream = new StreamingOutput() { //实现stream
@Override
public void write(OutputStream output) throws IOException, WebApplicationException {
try {
output.write(fjnr); //把数据库读出的字节输出到stream
} catch (Exception e) {
throw new WebApplicationException(e);
}
}
};
//ResponseBuilder builder = Response.ok(fjnr, "application/x-download;charset=utf-8");
ResponseBuilder builder = Response.ok(stream); //用stream返回
try {
builder.header("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fjmc, "UTF-8") + "");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Response response =builder.build();
return response;
}

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧