如何解决Express、Multer 和 Cloudinary 未返回完整的 Cloudinary 响应
我使用 Multer/multer-storage-cloudinary 将图像直接上传到 Cloudinary,而不是首先将其上传到本地临时目录,然后将其发送到 Cloudinary:
const express = require('express');
const router = express.Router({mergeParams:true});
if (app.get('env') == 'development'){ require('dotenv').config(); }
const crypto = require('crypto');
const cloudinary = require('cloudinary').v2;
const { CloudinaryStorage } = require('multer-storage-cloudinary');
const multer = require('multer');
const { storage } = require('../cloudinary');
const upload = multer({storage});
//configure cloudinary upload settings
cloudinary.config({
cloud_name:process.env.CLOUDINARY_NAME,api_key: process.env.CLOUDINARY_API_KEY,api_secret: process.env.CLOUDINARY_API_SECRET
});
const storage = new CloudinaryStorage({
cloudinary: cloudinary,folder: ('book_tracker/'+process.env.CLOUDINARY_FOLDER+'posts'),allowedFormats: ['jpeg','jpg','png'],filename: function (req,file,cb) {
let buf = crypto.randomBytes(16);
buf = buf.toString('hex');
let uniqFileName = file.originalname.replace(/\.jpeg|\.jpg|\.png/ig,'');
uniqFileName += buf;
console.log(req.body);
cb(undefined,uniqFileName );
}
});
const middleware = {
function asyncErrorHandler: (fn) =>
(req,res,next) => {
Promise.resolve(fn(req,next))
.catch(next);
}
}
/* POST create user page */
router.post('/register',upload.single('image'),asyncErrorHandler(postRegister));
我遇到的是我在 req.file
中得到的响应不是包含 public_id 等的完整 Cloudinary 响应。而是这样的:
{
fieldname: 'image',originalname: 'My Headshot.jpg',encoding: '7bit',mimetype: 'image/jpeg',path: 'https://res.cloudinary.com/<cloudinary_name>/image/upload/v1611267647/<public_id>.jpg',size: 379632,filename: '<public_id>'
}
我已经有一段时间没有使用 multer-storage-cloudinary,尽管 storage
是直接从一个可以返回正确信息的旧项目中获取的。我需要设置 multer 或 multer-storage-cloudinary 中的某些内容,以便将完整的 cloudinary 响应放入 req.file 中吗?
解决方法
multer-storage-cloudinary
包是一个以简化方式集成了 multer 和 Cloudinary 的第三方包,但它没有公开来自 Cloudinary SDK 或 API 的所有可能的选项或响应
在您的示例中,它没有从 Cloudinary 返回完整的 API 响应,而是返回字段的子集,因为 file
对象的 filename
、path
和 size
属性取自 Cloudinary API 响应(分别来自 API 响应的 public_id
、secure_url
和 bytes
属性),但其他字段未映射:{{3} }
如果您需要完整的响应值集(或一些尚未映射的特定值),您可以:
- 要求包维护者添加对其他字段的支持
- fork 包并自己映射其他字段;字段映射在这里,但我不确定还有什么可能需要更改:https://github.com/affanshahid/multer-storage-cloudinary#file-properties
- 从使用用于包装 Cloudinary SDK 的包切换到直接在您自己的代码中使用 Cloudinary SDK,以便您可以直接处理响应。
- 保持原样,单独调用 Cloudinary Admin API 以获取图像的其他详细信息:https://github.com/affanshahid/multer-storage-cloudinary/blob/1eb903d44ac6dd42eb1ab655b1e108acd97ed4ca/src/index.ts#L83-L86
- 保持原样,但添加一个 notification_url 以便与 API 调用响应一样,新上传的详细信息将通过 HTTP POST 请求发送到您选择的 URL:https://cloudinary.com/documentation/admin_api#get_resources
- notification_url 可以在上传 API 调用、上传预设中指定,也可以在 Cloudinary 帐户设置中的帐户级别指定。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。