我们将文档或者图片保存的数据库中的大字段blob或者longBlob中,其中字段对应的实体属性一般是byte[]类型。
首先,请获取附件的相关信息
Attachment attachment = fileService.getFileById("3b63778e-b1d1-454d-98da-916f12a18116");
byte[] filecontent_blob = attachment.getFilecontent_blob();
1.下载图片
response.reset();
// 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(attachment.getFilename(),"UTF-8"));
response.setContentType("application/octet-stream");
OutputStream os = response.getOutputStream();
os.write(filecontent_blob);// 输出文件
os.flush();
os.close();
2.输出在网页
OutputStream out = response.getOutputStream();
out.write(filecontent_blob);
out.flush();
out.close();
3.保存到硬盘
String URL="d:/"+attachment.getFilename();
File file=new File(URL);
if(file.exists()){
file.delete();
}
file=new File(URL);
FileOutputStream fos=new FileOutputStream(file);
fos.write(filecontent_blob,0,filecontent_blob.length);
fos.flush();
fos.close();
望对大家有所帮助