sorry, very new to Node.js here. I am having trouble getting my head around a good strategy to upload files from an iphone client into a node.js server and storing it on the server side.
For now, I can accept a binary file on the server and save it to the filesystem with the following code:
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();
});
With this code, I first accept a multipart form upload of a jpeg from the iphone into the /tmp directory, then I rename and move the file to the ./uploads directory. My problem is how to save this file into the DB.
From what I've read, I have three choices (I think!)
I have been trying #3 using this module I found called gridfs-stream (Since I am using mongoose), but I really don't understand the source code in the package.
My question is a two-parter: Among the 3 choices above, would #3 indeed be the way to go? If so, I really need some help on understanding how to use gridfs-stream.
I know the following code is wrong, but this is my attempt thus far to see if I can slot it into my existing upload code:
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();
});
Any help would be appreciated. Thank you!