nodejs接入阿里云OSS实现图片管理丨技术开发分享录

nodejs接入阿里云OSS实现图片管理

{{ detail.nickname }}

转载 翻译 {{ formatTime(detail.create_time) }} 字数 {{ detail.content && detail.content.length }} 阅读 {{ detail.read_num }} {{ formatTag(v) }}

"入门篇:[从一步步购买到简单代码实现](https://blog.csdn.net/weixin_33862993/article/details/94085772)\n\n- 阿里云Node.js SDK文档:https://help.aliyun.com/document_detail/32068.html?spm=a2c4g.11186623.6.1393.ac767f85oNNTLo\n- 阿里云Browser.js SDK文档(前端直通OSS):https://help.aliyun.com/document_detail/64041.html?spm=a2c4g.11186623.6.1465.629d165aytoAWM\n- 阿里云OSS客户端:https://market.aliyun.com/products/53690006/cmgj000281.html#sku=biaozhunban\n\n![QQ截图20201116102014.jpg](/images/articles/QQ截图2020111610201420201116102054.jpg =600x378)\n\n>[success] 使用Browser.js可以减小服务器压力,不过其暴露的方法比较少,具体要不要用看业务需求了\n\n开发时可以先开启Bucket ACL公众读权限,这样就可以通过URL访问OSS上的图片了\n\n![image.png](/images/articles/image20201114211959.png)\n\n当然也可以通过代码设置\n\n```\nconst oss = require('ali-oss');\n\nconst store = oss({\n// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。\n  accessKeyId: '<your access key>',\n  accessKeySecret: '<your access secret>',\n  bucket: '<your bucket name>',\n  // 获取当前bucket所在的region。\n  region: 'oss-cn-hangzhou'\n});\n  //设置指定文件的访问权限为公共读。\nawait store.putACL('<object name>', 'public-read');\n```\n\n## 一、安装\n\n使用nodejs接口oss,需要安装`ali-oss`依赖\n\n```bash\n> npm install ali-oss --save\n```\n\n实现上传图片的功能,还需要安装`multer`依赖\n\n```bash\n> npm install multer --save\n```\n\n## 二、代码封装\n\n1、把OSS实例配置放到utils/index.js里,代码如下:\n\n```\n// oss客户端\nconst ossClient = new OSS({\n  region: 'oss-cn-shanghai',\n  accessKeyId: '<your access key>',\n  accessKeySecret: '<your access secret>',\n  bucket: '<your bucket name>'\n});\n\nmodule.exports = {\n  ossClient\n};\n```\n\n各区对应的region英文:https://help.aliyun.com/document_detail/31837.html?spm=a2c4g.11186623.2.7.341d1fdcgqBCVH#concept-zt4-cvy-5db\n\n2、multer配置\n\n```\nconst multer = require('multer');\nconst storage = multer.diskStorage({\n  // 指定上传目录\n  destination(req, file, cb) {\n    cb(null, 'uploads');\n  },\n  // 修改文件名称\n  filename(req, file, cb) {\n    let fileChunkArr = file.originalname.split('.');\n    let extName = '.' + fileChunkArr.pop();\n    let fileName = fileChunkArr.join('.') + Date.now() + extName;\n    cb(null, fileName);\n  }\n});\nconst upload = multer({\n  limits: {\n    fileSize: 2 * 1024 * 1024, // 限制文件大小2M\n  },\n  fileFilter(req, file, cb) {\n    if (/image\\/(png|jpg|jpeg|gif|bmp|webp)$/.test(file.mimetype)) { // 验证图片\n      cb(null, true);\n    } else {\n      cb(null, false);\n    }\n  },\n  storage\n});\n```\n\n## 三、功能实现\n\n### 1、上传\n\n以批量上传为例,代码如下:\n\n```html\n<form method=\"post\" action=\"/uploads\" enctype=\"multipart/form-data\">\n    <input type=\"file\" name=\"file\" multiple>\n    <button type=\"submit\">上传</button>\n</form>\n```\n\n```\nconst utils = require('../utils');\n\n// 批量上传,上传到OSS images目录下\nrouter.post('/uploads', upload.array('file'), (req, res, next) => {\n  req.files.forEach(async item => {\n    await utils.ossClient.put('images/'+item.filename, item.path);\n    // 上传完删除原文件\n    fs.unlinkSync(item.path);\n  });\n});\n```\n### 2、下载\n\n以ajax下载为例,代码如下:\n\n```{9-12}\n$('#js_download').click(function() {\n    $.ajax({\n        url: '/download',\n        success: function(res) {\n            var a = document.createElement('a');\n            a.download = res.data.filename;\n            a.style.display = 'none';\n\n            var data = '';\n            res.data.content.data.forEach(function(v, i) {\n                data += String.fromCharCode(v)\n            }); \n\n            var image = \"data:image/jpg;base64,\"+window.btoa(data)\n            a.href = image;\n\n            document.body.appendChild(a);\n            a.click();\n            a.remove();\n        }\n    })\n});\n```\n\n```\nrouter.get('/download', async (req, res, next) => {\n  // let result = await utils.ossClient.get('images/201110-1.jpg', '201110-1.jpg'); // content: null,直接下载到项目下\n\n  let result = await utils.ossClient.get('images/201110-1.jpg'); // content: buffer,不下载,但会返回图片buffer数据\n  res.json({\n    status: true,\n    data: {\n      content: result.content,\n      filename: '201110-1.jpg'\n    }\n  })\n});\n```\n\n### 3、删除\n\n以批量删除为例,代码如下:\n\n```\nrouter.get('/deletes', (req, res, next) => {\n  [\n    'images/201110-1.jpg',\n    'images/201110-2.jpg'\n  ].forEach(async file => {\n    await utils.ossClient.delete(file);\n  });\n});\n```\n\n## 列表 \n\n列出指定目录图片,限制最多10条数据\n\n```\nlet result = await utils.ossClient.list({\n  prefix: 'images/',\n  'max-keys': 10\n});\n```\n\nresult会返回 `isTruncated` 和 `nextMarker` 字段\n\n>[warning] 注意:objects数据里第一个是目录数据\n\n如果想要分页获取的话,直接指定marker配置max-keys即可,这样会返回marker后的限制条数\n\n```\n// 根据nextMarker继续列出文件。\nif (result.isTruncated) {\n  result = await utils.ossClient.list({\n    prefix: 'images/',\n    'max-keys': 10\n    marker: result.nextMarker\n  });\n}\n```"
PS:写作不易,如要转裁,请标明转载出处。

如果此篇对您有帮助,可小额赞助,以兹鼓励!

猜你想看