3

抱歉,这里对 Node.js 很陌生。我很难找到一个好的策略,将文件从 iphone 客户端上传到 node.js 服务器并将其存储在服务器端。

现在,我可以接受服务器上的二进制文件并使用以下代码将其保存到文件系统:

app.post('/upload', function(req, res){

    // get the temporary location of the file
    var tmp_path = req.files.pic.path;
    // set where the file should actually exists - in this case it is in the "images" directory
    var target_path = './uploads/' + req.files.pic.name;
    // move the file from the temporary location to the intended location
    fs.rename(tmp_path, target_path, function(err) {
        if (err) throw err;
        // delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files
        fs.unlink(tmp_path, function() {
            if (err) throw err;
            res.send('File uploaded to: ' + target_path + ' - ' + req.files.pic.size + ' bytes');
        });
    });

    console.log(req.files.pic.name);
    res.send('DONE', 200);
    res.end();
});

使用此代码,我首先接受从 iphone 到 /tmp 目录的 jpeg 的多部分表单上传,然后我重命名并将文件移动到 ./uploads 目录。我的问题是如何将此文件保存到数据库中。

根据我的阅读,我有三个选择(我认为!)

  1. 将文件保存到某个上传目录并将本地路径存储到 mongodb 以供以后访问
  2. 使用缓冲区将文件本身保存到 MongoDb
  3. 使用 grid-fs 保存文件。

我一直在尝试#3,使用我发现的名为 gridfs-stream 的模块(因为我使用的是 mongoose),但我真的不明白包中的源代码。

我的问题是两部分的:在上面的 3 个选择中,#3 确实是要走的路吗?如果是这样,我真的需要一些帮助来理解如何使用 gridfs-stream。

我知道下面的代码是错误的,但这是我迄今为止的尝试,看看我是否可以将它插入到我现有的上传代码中:

app.post('/upload', function(req, res){

    // get the temporary location of the file
    var tmp_path = req.files.pic.path;
    // set where the file should actually exists - in this case it is in the "images" directory
    var target_path = './uploads/' + req.files.pic.name;
    // move the file from the temporary location to the intended location
    fs.rename(tmp_path, target_path, function(err) {
        if (err) throw err;

        var conn = mongoose.createConnection('localhost', 'myahkvoicedb');

        conn.once('open', function () {
            var gfs = Grid(conn.db, mongoose.mongo);

            // all set!
            var writestream = gfs.createWriteStream('req.files.pic.name');
            fs.createReadStream('./uploads/').pipe(writestream);

            /* // APP CRASHES HERE WITH THE FOLLOWING:
            stream.js:81
            throw er; // Unhandled stream error in pipe.
            ^
            Error: EISDIR, read
            */
        })


        // delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files
        fs.unlink(tmp_path, function() {
            if (err) throw err;
            res.send('File uploaded to: ' + target_path + ' - ' + req.files.pic.size + ' bytes');
        });
    });

    console.log(req.files.pic.name);
    res.send('DONE', 200);
    res.end();
});

任何帮助,将不胜感激。谢谢!

4

0 回答 0