• nodejs, 阿里oss上传下载图片


    const archiver = require('archiver')
    const send = require('koa-send')
    const oss = require('ali-oss').Wrapper

    const path = require('path')

    const uuid = require('uuid')

    const fse = require('fs-extra')

    const store = oss({
    accessKeyId: 'fdfdffeffjjfjjf',
    accessKeySecret: 'fdjfjdfkdjfdkfdjfdjfdjf',
    region: `${ossRegin}`
    timeout: 120000
    })
    store.useBucket(`${useBucket}`) 

    const router = new Router()

    1.从oss上打包下载图片

    router.get('down', async (ctx, next) => {

    const photoKey = await cache.getAsync(ctx.params.key);
    if (!photoKey) {
    throw {
    message: 'file not exists',
    router: ctx._url
    }
    }
    const photoObj = JSON.parse(photoKey);
    const photoIds = photoObj.photoIds;
    const photoInfo = await model.photo.find({
    _id: {
    $in: photoIds
    }
    }, {
    _id: 0,
    'originalInfo.path': 1
    })
    if (!photoInfo) {
    throw {
    message: 'photo not exists',
    router: ctx._url
    }
    }
    const zipath = `${uuid.v4().replace(/-/g, '')}.zip`;
    const output = fse.createWriteStream(zipath);
    const zipAchiver = archiver('zip');
    for (let photo of photoInfo) {
    let photoPath = photo.originalInfo.path;
    let photoName = uuid.v1().replace(/-/g, '') + path.extname(photoPath);
    const rs = await store.getStream(photoPath);
    zipAchiver.append(rs.stream, {
    'name': photoName
    })
    }
    zipAchiver.pipe(output);
    const fileSize = await fse.stat(zipath);
    const size = Math.round(Number(fileSize.size) / 1024 / 1000);
    if (size > 300) {
    ctx.body = {
    maxSize: 300,
    size: size
    }
    return
    }
    await zipAchiver.finalize();
    ctx.set('Content-Type', 'application/zip');
    ctx.attachment(zipath);
    await send(ctx, zipath);
    fse.unlink(zipath);
    })

    2.上传图片到oss

    cosnt fileName =`oss/${yearstr}/${dayStr}/photos/tn/${seconds}.jpg`

    const buffer = new Buffer(ctx.req.file,'base64')

    const rs = await store.put(fileName, buffer, {
    timeout: 120000
    })

    return rs.name

  • 相关阅读:
    MySQL事务
    MySQL索引
    MySQL基础
    设计模式之单例模式
    设计模式之适配器模式
    zookeeper学习记录第二篇-----安装、配置、启动
    Scrapy 安装
    shiro
    python 爬虫简介以及使用方法
    linux VMware使用
  • 原文地址:https://www.cnblogs.com/qiyc/p/10405257.html
Copyright © 2020-2023  润新知