ExpressJS中的“VARCHAR”和服务器硬盘中的映像存储图像在数据库中的位置

我如何在ExpressJS中做到这一点?

  • 使用VARCHAR数据types而不是任何BLOB或其他binary数据types来存储图像在数据库中的位置。
  • 然后将该映像存储在服务器harddisk中可能的映像空间/public/images/

我是新来expression。

任何示例来实现这个?

你可以做的是使用multipart中间件 ,它自动将file upload到磁盘,然后提供一个req.files对象。

 app.use('/upload', express.multipart({ uploadDir: '/public/images' })); 

一旦你configuration了这个,在你的请求处理程序中,你可以得到上传path(参见multipart中间件内部使用的multipart 文档 ):

 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); }); 

你可以尝试这个上传图像,你将只存储图像的path,并将该图像保存在您的存储

 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.'}); } }