Итак, моя главная цель — сохранить изображения в пользовательских документах в mongoDB. До сих пор мне удавалось сохранять загруженное изображение в папку временных изображений моего сервера, и я не могу понять, как отправить его в mongoDB.
Обратите внимание, что эта функция будет использоваться, когда новый пользователь зарегистрируется на моем сайте, и он сможет загрузить изображение профиля в процессе регистрации.
На данный момент я сделал:
<form method="post" enctype="multipart/form-data" action="/file-upload">
<input type="file" name="thumbnail">
<input type="submit">
// we need the fs module for moving the uploaded files
var fs = require('fs');
app.post('/file-upload', function(req, res) {
// get the temporary location of the file
var tmp_path = req.files.thumbnail.path;
// set where the file should actually exists - in this case it is in the "images" directory
var target_path = './images/' + req.files.thumbnail.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.thumbnail.size + ' bytes');
});
});
});
The above code works and I can see the image being uploaded into my images folder on the server but how can I post this mongoDB?