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

猜你喜欢

转载自www.cnblogs.com/qiyc/p/10405257.html