发布原因:今天在维护公司一个很早的系统过程当中,需求需要开发一个文件下载功能,但是我一看这技术栈,真就吓一跳。但是没办法,还是得依着它来。就看了一下老系统的代码,发现他们是将文件直接以Blob形式存储数据库中,于是就出现了下面的小案例!
后端servlet实现代码:
private static final String[] contentTypes={"application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/pdf","image/jpeg","image/png","application/zip"};
private static final String[] suffixs={"docx","xlsx","pdf","jpeg","png","zip"};
/**
* 文件下载
* @param request
* @param response
*/
private void keepView(HttpServletRequest request, HttpServletResponse response) {
//数据所绑定的id
String id = request.getParameter("id");
//连接数据库
Connection conn = ConnDataBase.getConnJdbc();
// 连接数据库并检索Blob数据
PreparedStatement stat = null;
ResultSet res = null;
try {
//构建sql查询语句
String sql="";
stat = conn.prepareStatement(sql);
res = stat.executeQuery();
Blob fileup=null;
String filename=null;
while (res.next()){
fileup = res.getBlob("FILEUP");
filename = res.getString("FILENAME");
}
String suffix = getFileExtension(filename);
String ct="";//文件类型
for (int i = 0; i < suffixs.length; i++) {
if (suffixs[i].equals(suffix)){
ct=contentTypes[i];
}else {
ct="application/octet-stream";
}
}
InputStream stream = fileup.getBinaryStream();
String fileName=new String(filename.getBytes("UTF-8"),"ISO-8859-1");
response.setContentType(ct);
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
// 写入响应
ServletOutputStream out = response.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = stream.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}catch (Exception e){
throw new RuntimeException("文件预览异常",e);
}finally {
// 关闭资源(使用try-with-resources可以自动关闭)
try { if (res != null) res.close(); } catch (SQLException e) {}
try { if (stat != null) stat.close(); } catch (SQLException e) {}
try { if (conn != null) conn.close(); } catch (SQLException e) {}
}
}
前端实现代码:
//下载的点击事件
function keepView(id) {
// 构建下载链接
var downloadUrl = 'PbmsInsectituationServlet?method=keepView&id=' + id;
// 创建一个新的 <a> 标签并设置 href 属性
var a = document.createElement('a');
a.href = downloadUrl;
a.download = 'hhhhhh.docx'; // 可选,可以指定下载文件的默认文件名
// 模拟点击 <a> 标签来触发下载
document.body.appendChild(a);
a.click();
// 然后从文档中移除 <a> 标签
document.body.removeChild(a);
}