jsp+servlet实现文件下载,文件以Blob类型数据存储在数据库中

发布原因:今天在维护公司一个很早的系统过程当中,需求需要开发一个文件下载功能,但是我一看这技术栈,真就吓一跳。但是没办法,还是得依着它来。就看了一下老系统的代码,发现他们是将文件直接以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);
	}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
将图片流文件blob形式存储数据库,可以按照以下步骤进行: 1. 读取图片流文件,将其转换为字节流。 2. 连接数据库,创建表格,其包含一个blob类型的列用于存储图片。 3. 将字节流插入到blob。 下面是一个Python代码示例,用于将图片流文件blob形式存储到MySQL数据库: ``` python import mysql.connector from io import BytesIO from PIL import Image # 读取图片并转换为字节流 img = Image.open('example.jpg') imgByteArr = BytesIO() img.save(imgByteArr, format='JPEG') imgByteArr = imgByteArr.getvalue() # 连接数据库 mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="mydatabase" ) # 创建表格 mycursor = mydb.cursor() mycursor.execute("CREATE TABLE images (id INT AUTO_INCREMENT PRIMARY KEY, image BLOB)") # 插入字节流到blob sql = "INSERT INTO images (image) VALUES (%s)" val = (imgByteArr,) mycursor.execute(sql, val) mydb.commit() print(mycursor.rowcount, "record inserted.") ``` 在代码,我们首先使用PIL库读取图片,并将其转换为字节流。然后,我们连接到MySQL数据库,并创建一个名为“images”的表格,其包含一个名为“image”的blob列。最后,我们将字节流插入到blob,并提交更改。 请注意,这只是一个示例代码,您需要根据自己的情况进行修改。例如,您需要替换数据库连接详细信息以及要存储的图像文件名。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值