1
0

oss.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import BaseService from '../../base';
  2. import * as qiniu from 'qiniu';
  3. import * as path from 'path';
  4. import * as moment from 'moment';
  5. import ImageSpaceInfo from '../../../entities/admin/image/space/info';
  6. /**
  7. * OSS Service
  8. */
  9. export default class OssService extends BaseService {
  10. /**
  11. * 将文件上传至七牛
  12. */
  13. async upload(file: any, namespace: string) {
  14. const { bucket, accessKey, secretKey, zone } = this.config.qiniu;
  15. const key = `${namespace}/${moment().format('YYYYMMDD_hhmmss')}${path.extname(file.filename)}`;
  16. const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
  17. const options = {
  18. scope: `${bucket}:${key}`,
  19. };
  20. const putPolicy = new qiniu.rs.PutPolicy(options);
  21. const qiniuConfig: any = new qiniu.conf.Config();
  22. qiniuConfig.zone = qiniu.zone[zone];
  23. const uploadToken = putPolicy.uploadToken(mac);
  24. return new Promise((resole, reject) => {
  25. const localFile = file.filepath;
  26. const formUploader = new qiniu.form_up.FormUploader(qiniuConfig);
  27. const putExtra = new qiniu.form_up.PutExtra();
  28. // 文件上传
  29. formUploader.putFile(uploadToken, key, localFile, putExtra, function(respErr,
  30. respBody, respInfo) {
  31. if (respErr) {
  32. reject(respErr);
  33. }
  34. if (respInfo.statusCode === 200) {
  35. resole(respBody);
  36. } else {
  37. reject(respErr);
  38. }
  39. });
  40. });
  41. }
  42. /**
  43. * 批量删除文件
  44. */
  45. async delete(images: ImageSpaceInfo[]) {
  46. const { bucket, accessKey, secretKey, zone } = this.config.qiniu;
  47. if (images && images.length > 0) {
  48. const keys = images.map(e => {
  49. const { key } = JSON.parse(e.extra);
  50. return qiniu.rs.deleteOp(bucket, key);
  51. });
  52. const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
  53. const qiniuConfig: any = new qiniu.conf.Config();
  54. qiniuConfig.zone = qiniu.zone[zone];
  55. const bucketManager = new qiniu.rs.BucketManager(mac, qiniuConfig);
  56. return new Promise((resolve, reject) => {
  57. bucketManager.batch(keys, (err, respBody, respInfo) => {
  58. if (err) {
  59. reject(err);
  60. } else {
  61. // 200 is success, 298 is part success
  62. if (parseInt(respInfo.statusCode) / 100 === 2) {
  63. resolve();
  64. } else {
  65. reject(respInfo.deleteusCode);
  66. console.log(respInfo.deleteusCode);
  67. console.log(respBody);
  68. }
  69. }
  70. });
  71. });
  72. }
  73. }
  74. }