Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

node.js - NodeJS mySQL Insert 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;
   });
  });
});

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try replacing:

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

with:

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...