请问我的代码出了什么问题?我想设置我的Web应用程序,以便当用户通过带有其他文本数据的表单发布图像时,该图像将被上传到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 POST请求
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);
})
}
答案 0 :(得分:0)
要上传到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);
});
});
}