问题
How I can do this in ExpressJS?
- Storing the location of the images in the database using
VARCHAR
datatype instead of anyBLOB
or otherbinary
datatype. - then store that image in server
harddisk
in possible image space/public/images/
i am new to express .
Any sample example to achieve this ?
回答1:
What you can do is use the multipart middleware, which automatically streams the file uploads to the disk, and then provides a req.files
object.
app.use('/upload', express.multipart({ uploadDir: '/public/images' }));
Once you've configured this, in your request handler, you can get the upload path (see multiparty's documentation, which is used internally by the multipart
middleware):
app.post('/upload', function (req, res, next) {
// Assuming the field name of the file in the form is 'file'
var path = req.files.file.path;
connection.query('your mysql query', next);
});
回答2:
you can try this for upload image you will store only path of image and save that image in your storage
var tempPath = req.files.image.path;
var ext = path.extname(req.files.image.name).toLowerCase();
var targetPath = path.resolve('./profile_img/' + user_id + ext);
// var targetPath = path.resolve('D:/Alex/Project/img/' + user_id + ext);
if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext === '.gif')
{
var inStr = fs.createReadStream(tempPath);
var outStr = fs.createWriteStream(targetPath);
inStr.pipe(outStr);
//save profile image to database
connection.query('update users set img_path=? where id=?',[targetPath,user_id],
function(err,imagesave){
if(!err)
{
console.log('Profile Picture Uploaded ..');
res.json({'code':200,'status':'Success','message':'Profile Picture Uploaded ..'});
return;
}
else
{
console.log('can not update ..',err);
res.json({'code':200,'status':'Success','message':err});
return;
}
});
}
else
{
console.log('File type must be image',err);
res.json(500, {error: 'Only image files are allowed.'});
}
}
来源:https://stackoverflow.com/questions/20213400/storing-the-location-of-the-images-in-the-database-using-varchar-in-expressjs