如何用Node.js通过Couchbase Sync Gateway上传指定格式图片至Couchbase
使用Node.js通过Couchbase Sync Gateway上传图片至Couchbase(Community Edition 5.0.0)
我来帮你搞定用Node.js通过Couchbase Sync Gateway上传图片的事儿,针对你用的5.0.0社区版,一步步来:
准备工作
- 先给项目装个HTTP请求库,比如
request(用你熟悉的axios也行),执行命令安装:npm install request --save - 确认Sync Gateway已经正常运行,并且你有目标数据库的写入权限。
具体实现步骤
1. 读取本地图片文件
用Node.js内置的fs模块读取图片的二进制数据,同时获取文件大小和MIME类型。
2. 调用Sync Gateway的REST API上传附件
Sync Gateway提供了专门的附件上传接口,我们通过PUT请求把图片数据发送过去就行。
完整代码示例
const fs = require('fs'); const request = require('request'); // 配置你的Sync Gateway和数据库信息 const syncGatewayUrl = 'http://localhost:4984'; // 替换成你的Sync Gateway地址 const dbName = 'your-target-db'; // 替换成你的数据库名 const docId = 'custom-image-doc-id'; // 自定义文档ID,不存在会自动创建 const localImagePath = './blahblahblah.jpeg'; // 本地图片路径 const attachmentFilename = 'blahblahblah.jpeg'; // 附件在文档中的文件名 // 读取图片文件 fs.readFile(localImagePath, (readErr, imageBuffer) => { if (readErr) { console.error('读取本地图片失败:', readErr); return; } // 获取文件大小和MIME类型 const fileLength = imageBuffer.length; const contentType = 'image/jpeg'; // 如果是其他类型,比如png就改成image/png // 构造上传请求选项 const uploadOptions = { url: `${syncGatewayUrl}/${dbName}/${docId}/_attachments/${attachmentFilename}`, method: 'PUT', headers: { 'Content-Type': contentType, // 如果你的Sync Gateway开启了认证,这里加Authorization头,比如Basic Auth // 'Authorization': 'Basic ' + Buffer.from('your-username:your-password').toString('base64') }, body: imageBuffer }; // 发送上传请求 request(uploadOptions, (uploadErr, response, resBody) => { if (uploadErr) { console.error('图片上传失败:', uploadErr); return; } if ([200, 201].includes(response.statusCode)) { console.log('图片上传成功!'); // 解析返回的文档,查看附件信息 const resultDoc = JSON.parse(resBody); console.log('文档中的附件结构:', resultDoc._attachments); } else { console.error(`上传失败,状态码: ${response.statusCode}`, resBody); } }); });
关于文档格式的说明
上传完成后,Sync Gateway会自动帮你生成符合要求的_attachments结构,不需要手动设置digest、revpos、stub这些字段。最终你的文档里的附件部分会是这样的:
"_attachments": { "blahblahblah.jpeg": { "content_type": "image/jpg", "digest": "md5-xxxxxxxxxxxxxx", "length": 99999, "revpos": 1, "stub": true } }
额外注意事项
- 如果要给已存在的文档添加附件,记得在请求URL后面带上文档的当前版本号,比如
?rev=1-xxxxxxxxx,否则会返回冲突错误。 - 为了更准确地获取MIME类型,你可以用
mime-types库自动识别,安装后用mime.lookup(localImagePath)就能得到对应类型。 - 确保Sync Gateway的配置文件里允许对该数据库的写入操作,比如在
databases配置块中设置write_access: "*"(测试环境用,生产环境要做权限控制)。
内容的提问来源于stack exchange,提问作者ranjith
相关产品推荐
相关产品推荐

