繁体   English   中英

如何使用节点中的multer将图像上传到cloudinary并用其他数据表达

[英]How can I upload image to cloudinary using multer in node and express with other data

请问我的代码有什么问题? 我想设置我的网络应用程序,以便当用户通过带有其他文本数据的表单发布图像时,图像将上传到 cloudinary 并返回 url,并与用户提交的其他数据一起保存所有记录到我的数据库。 请注意,我使用的是 pg-promise 库和 postgres DB。 我在下面包含我的代码以供参考。

我的数据架构

CREATE TABLE photo_table (
  post_id uuid REFERENCES post(post_id) NOT NULL,
  photo_by text REFERENCES m_user(username),
  title text NOT NULL,
  description text NOT NULL,
  photo_url text NOT NULL,
  category text,
  location text,
  campaign text,
  posted_on timestamp NOT NULL default now(),
  updated_on timestamp NOT NULL default now(),
  PRIMARY KEY (pid)
);

我的 CLOUDINARY & MULTER 配置文件

const cloudinary = require('cloudinary').v2;
const multer = require("multer");
const cloudinaryStorage = require("multer-storage-cloudinary");

cloudinary.config({
  cloud_name: 'xxxxxxxx',
  api_key: 'xxxxxxxx3115',
  api_secret: 'xxxxxxxxxxxxYXpmAAr3b04'
}); 

const storage = cloudinaryStorage({
  cloudinary: cloudinary,
  folder: "photos",
  allowedFormats: ['jpg', 'jpeg', 'png'],
  transformation: [{ width: 960, height: 960, crop: "limit" }],
  filename: (req, file, callback) => {
    const name = file.originalname.split(' ').join('_');
    callback(undefined, name);
  }
});

module.exports = multer({storage: storage}).single('photo');

我的 API 发布请求

const multer = require('../middlewares/multer/photo-config'); 

//multer 在我的路由文件中被调用,如下行所示

router.post('/', multer, photoCtrl.addPhoto);

下面的功能是我的控制器请求

function addPhoto(req, res, next) {
  const queryPhoto = 'INSERT INTO post (post_type, created_on) VALUES($1, $2) RETURNING pid'
  db.tx('my-transaction', t => {
    return t.one(queryPhoto, ['photo', 'now()'])
        .then(post => {
          const data = {
        photo_by: req.body.username,
        title: req.body.title,
        description: req.body.description,
        photo_url: req.files,
        category: req.body.category,
        location: req.body.location,
        campaign: req.body.campaign
      }
      const insertPhotoText = `INSERT INTO photo_table (pid, photo_by, title, description, photo_url, category, location, campaign, posted_on, updated_on) 
                                   VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`
      const insertPhotoValues = [post.pid, data.photo_by, data.title, data.description, data.photo_url, data.category, data.location, data.campaign, 'now()', 'now()']
              return t.none(insertPhotoText, insertPhotoValues);
        });
})
    .then(function () {
      res.status(200)
        .json({
          status: 'success',
          message: 'One photo added'
        });
    })
    .catch(function (err) {
      return next(err);
    })
  }
  

为了上传到 Cloudinary,您需要调用 uploader() 方法: https ://cloudinary.com/documentation/node_integration

示例代码:

app.post('/', upload.any([{ name: "test" }]), (req, res) => {
        var files=req.files;
        if(files){
            files.forEach(function(file){
                cloudinary.uploader.upload(file.path, function(result) { 
                console.log(result);
            });
            });
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM