Node.js将一个文件夹的文件装载到MySQL数据库BLOB列,并将BLOB列下载到另一个文件夹

本文介绍了如何使用Node.js和MySQL进行Blob类型数据的处理,包括从文件系统读取图片并插入到`bindata`表中,以及从数据库检索并下载文件。重点在于数据库操作的示例和BLOB数据的处理方式。
摘要由CSDN通过智能技术生成
/*
 DDL:
 CREATE TABLE `bindata` (
 `id` INT NOT NULL AUTO_INCREMENT,
 `data` BLOB,
 PRIMARY KEY (`id`)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
 */

/* global Buffer */

const fs = require('fs');
const mysql = require("mysql");

pool = mysql.createPool({
    "connectionLimit": 10,
    "host": "localhost",
    "port": 3306,
    "user": "root",
    "password": "root",
    "database": "blob",
    "timezone": 'utc',
    // Enables query format like this:
    // `connection.query("UPDATE x SET col=:v1" , { v1: 999 }, ...`
    //
    // NOTE: How to insert binary data:
    // ```
    // // Read BLOB:
    // pool.query(`SELECT * FROM example`, function(err, res) {
    //   const buf = new Buffer(res[0].data); // `data` column type is BLOB!
    //   // Write BLOB:
    //   pool.query("INSERT INTO example(data) VALUES(BINARY(:buf))", { buf }, ...);
    // }
    // ```
    queryFormat: function (query, values) {
        if (!values)
            return query;
        return query.replace(/\:(\w+)/g, function (txt, key) {
            if (values.hasOwnProperty(key)) {
                return this.escape(values[key]);
            }
            return txt;
        }.bind(this));
    }
});

// directory path
const dir = './InputFiles/';

// list all files in the directory
try {
    const files = fs.readdirSync(dir);

    // files object contains all files names
    // log them on console
    files.forEach(file => {
        console.log(file);
        // Read buffer of an image file:
        const data = readImageFile("./InputFiles/" + file); // `data`'s type is Buffer
        const name = file.toString();
        pool.query("INSERT INTO `bindata`(name,data) VALUES(:name,BINARY(:data))", {name, data}, function (err, res) {
            if (err)
                throw err;
            console.log("BLOB data inserted!");
        });

    });

} catch (err) {
    console.log(err);
}


function readImageFile(file) {
    // read binary data from a file:
    const bitmap = fs.readFileSync(file);
    const buf = Buffer.from(bitmap);
    return buf;
}

/*
 DDL:
 CREATE TABLE `bindata` (
 `id` INT NOT NULL AUTO_INCREMENT,
 `data` BLOB,
 PRIMARY KEY (`id`)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
 */

const fs = require("fs");
const mysql = require("mysql");

pool = mysql.createPool({
    "connectionLimit": 10,
    "host": "localhost",
    "port": 3306,
    "user": "root",
    "password": "root",
    "database": "blob",
    "timezone": 'utc',
    // Enables query format like this:
    // `connection.query("UPDATE x SET col=:v1" , { v1: 999 }, ...`
    //
    // NOTE: How to insert binary data:
    // ```
    // // Read BLOB:
    // pool.query(`SELECT * FROM example`, function(err, res) {
    //   const buf = new Buffer(res[0].data); // `data` column type is BLOB!
    //   // Write BLOB:
    //   pool.query("INSERT INTO example(data) VALUES(BINARY(:buf))", { buf }, ...);
    // }
    // ```
    queryFormat: function (query, values) {
        if (!values)
            return query;
        return query.replace(/\:(\w+)/g, function (txt, key) {
            if (values.hasOwnProperty(key)) {
                return this.escape(values[key]);
            }
            return txt;
        }.bind(this));
    }
});


const outputfile = "output.png";


// Check to read it from DB:
pool.query("select * from `bindata`", function (err, res) {
    if (err)
        throw err;
    Object.keys(res).forEach(function (key) {
        var row = res[key];
        console.log(row.name);
        const data = row.data;
        console.log("BLOB data read!");
        // Converted to Buffer:
        const buf = new Buffer(data, "binary");
        // Write new file out:
        fs.writeFileSync("DownloadFiles/" + row.name, buf);
        console.log("New file output:", row.name);
    });

});


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值