NodeJS mySQL插入Blob [英] NodeJS mySQL Insert Blob

查看:72
本文介绍了NodeJS mySQL插入Blob的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一点帮助 使用NodeJS和MySQL blob插入.

I need a little help with NodeJS and MySQL blob insertion.

这是我正在使用的代码段

Here's the code snippet i'm using

fs.open(temp_path, 'r', function (status, fd) {
    if (status) {
        console.log(status.message);
        return;
    }
    var buffer = new Buffer(getFilesizeInBytes(temp_path));
    fs.read(fd, buffer, 0, 100, 0, function (err, num) {
    var query ="INSERT INTO `files` (`file_type`, `file_size`, `file`) VALUES ('img', " + getFilesizeInBytes(temp_path) + ",'" + buffer + "' );";
    mySQLconnection.query(query, function (er, da) {
   if (er)throw er;
   });
  });
});

查询将文件插入表中,我得到正确的文件大小,但是当我尝试 检索文件并打开它(例如PDF文件),我收到一条消息,说 该文件已损坏.

Query inserts the file in the table and I get the correct file size, but when I try to retrieve the file and open it ( for example a PDF file ) I get a message saying that the file is corrupted.

我从文件读取的缓冲区一定做错了.

I must be doing something wrong with the buffer reading from the file.

推荐答案

尝试替换:

var query ="INSERT INTO `files` (`file_type`, `file_size`, `file`) VALUES ('img', " + getFilesizeInBytes(temp_path) + ",'" + buffer + "' );";
mySQLconnection.query(query, function (er, da) {

具有:

var query = "INSERT INTO `files` SET ?",
    values = {
      file_type: 'img',
      file_size: buffer.length,
      file: buffer
    };
mySQLconnection.query(query, values, function (er, da) {

您可能还想将file: buffer更改为file: buffer.slice(0, 100),因为您只读取文件的前100个字节.如果是buffer.length > 100,那么在buffer中的前100个字节之后,您可能会得到一堆额外的垃圾字节.

You may also want to change file: buffer to file: buffer.slice(0, 100) since you are only reading the first 100 bytes of the file. If buffer.length > 100 then you may end up with a bunch of extra garbage bytes after the first 100 bytes in buffer.

这篇关于NodeJS mySQL插入Blob的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆