(共556篇)
全部分类

OSS上传及文件处理案例
[ Case ] 

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
import axios from "axios";
import Vue from "vue";

import imageCompressor from "browser-image-compression";
import { nanoid } from "nanoid";
import moment from "moment";

/**
 * 项目中要使用各自的接口请求函数, 来保证接口验签功能的正常使用
 */
const http = axios.create({
  baseURL: "https://api..com",
  timeout: 5000,
});

import OSS from "ali-oss";

class OssService {
  constructor(options) {
    if (!options.refreshToken) {
      throw new Error("OSS refreshToken can not be empty");
    }
    if (!options.buckets) {
      throw new Error("OSS buckets can not be empty");
    }

    this.options = options;
    this.log =
      options.log ||
      function (desc) {
        console.log(desc);
      };
    this.buckets = options.buckets;
    this.refreshToken = options.refreshToken;

    this.token = "";
    this.clientsMap = {};
    this.initCacheList = [];
  }

  async getAuthData() {
    this.log("getAuthData");
    this.loadingAuthData = true;
    this.authData = await this.refreshToken();
    this.refreshSTSTime = new Date().getTime();
    this.loadingAuthData = false;
    this.initCacheList.forEach((item) => this.initClient(item));
    this.initCacheList = [];
  }

  async initClient(item) {
    this.log("initClient", item);
    if (
      !this.authData ||
      new Date().getTime() - this.refreshSTSTime > 1000 * 10
    ) {
      await this.getAuthData();
    }
    const { name, resolve } = item;
    if (this.clientsMap[name]) {
      resolve(this.clientsMap[name]);
      return;
    }

    const existBucket = this.buckets.find((item) => item.bucket === name);
    if (!existBucket) {
      throw new Error(`没找到bucket: ${name}`);
    }
    const options = {
      ...existBucket,
      ...this.authData,
      refreshSTSToken: this.refreshToken,
      refreshSTSTokenInterval: 1000 * 10,
    };

    const client = new OSS(options);
    this.clientsMap[name] = client;
    resolve(client);
  }
  /**
   * 如果正在请求authData, 挂起
   */

  init(name) {
    this.log("init", name);
    return new Promise((resolve) => {
      if (this.loadingAuthData) {
        this.initCacheList.push({ name, resolve });
      } else {
        this.initClient({
          name,
          resolve,
        });
      }
    });
  }

  async put(fileName, file, name = "") {
    const client = await this.init(name);
    return client.put(fileName, file);
  }

  async big({ fileName, file, name = "", callback, meta = {} }) {
    const client = await this.init(name);
    return client.multipartUpload(fileName, file, {
      progress(p, checkpoint) {
        callback(p, checkpoint);
      },
      meta,
    });
  }

  async get({
    fileName,
    expires = 36000,
    name = "",
    width = "",
    quality,
    process,
  }) {
    const client = await this.init(name);
    const signatureOptions = {
      expires,
    };
    if (process) {
      signatureOptions.process = process;
    } else if (width || quality) {
      signatureOptions.process = "image/auto-orient,1";
      if (width) {
        signatureOptions.process += `/resize,m_lfit,w_${width}`;
      }
      if (quality) {
        signatureOptions.process += `/quality,q_${quality}`;
      }
    }
    const res = await client.signatureUrl(fileName, signatureOptions);
    return res;
  }

  processUrl(a, b) {
    if (
      Object.prototype.toString.call(a).toLowerCase().slice(-7, -1) ===
        "string" &&
      !b &&
      /^\?x-oss-process=/g.test(a)
    ) {
      return a;
    }

    let str = "";
    if (
      Object.prototype.toString.call(a).toLowerCase().slice(-7, -1) === "number"
    ) {
      str += `?x-oss-process=image/auto-orient,1/resize,m_lfit,w_${a}`;
      if (
        b &&
        Object.prototype.toString.call(b).toLowerCase().slice(-7, -1) ===
          "number"
      ) {
        str += `/quality,q_${b}`;
      }
    }
    return str;
  }

  async download(fileName, downloadName = "", name = "") {
    const client = await this.init(name);
    let restr = "attachment; ";
    downloadName = downloadName || fileName.split("/").slice(-1)[0];
    restr += `filename=${encodeURIComponent(downloadName)}`;

    const response = {
      "content-disposition": restr,
    };
    const res = await client.signatureUrl(fileName, { response });
    window.open(res, "_blank");
  }
}

const ossInstance = new OssService({
  refreshToken: async () => {
    const res = await http.get("/admall-user/api/oss/sts-token");
    const {
      accessKeyId,
      accessKeySecret,
      securityToken: stsToken,
    } = res.data.content;
    return {
      accessKeyId,
      accessKeySecret,
      stsToken,
    };
  },
  buckets: [
    {
      region: "oss-cn-qingdao",
      bucket: "admalltech-public",
    },
    {
      region: "oss-cn-qingdao",
      bucket: "admalltech-private",
    },
    {
      region: "oss-cn-qingdao",
      bucket: "admalltech-im",
    },
  ],
});

function compressImg(file, quality) {
  return new Promise((resolve) => {
    if (!/^image\/(png|jpg|jpeg|bmp|gif)$/.test(file.file.type)) {
      resolve(file);
      return;
    }
    try {
      const reader = new FileReader();
      reader.onload = async function (a) {
        console.log(a);
        const blob = new Blob([a.target.result]);
        console.log(blob);
        const newFile = new File(
          [blob],
          file.file.name.replace(/\.(png|bmp)$/, ".jpg"),
          {
            type: "image/jpeg",
          }
        );

        const res = await imageCompressor(newFile, {
          useWebWorker: true,
          initialQuality: quality,
        });
        const compressedFile = new File([res], file.file.name, {
          type: res.type,
        });
        file.file = compressedFile;
        resolve(file);
      };
      reader.readAsArrayBuffer(file.file);
    } catch (e) {
      console.log(e);
      file.error = e;
      resolve(file);
    }
  });
}

function mapFileName(file) {
  return new Promise(async (resolve) => {
    // 只对图片文件做改名处理
    if (!/^image\/(png|jpg|jpeg|bmp|gif)$/.test(file.file.name)) {
      try {
        file.fileName =
          moment().format("YYYYMMDD") +
          "/" +
          nanoid(32) +
          "." +
          file.file.name.split(".").slice(-1)[0];
        console.log(file.file.name);
        console.log(file.fileName);
        resolve(file);
      } catch (e) {
        file.error = e;
        resolve(file);
      }
    } else {
      try {
        const img = new Image();
        const objectUrl = URL.createObjectURL(file.file);
        img.onload = function () {
          URL.revokeObjectURL(objectUrl);
          console.log(`_w${img.width}_h${img.height}.`);
          file.fileName =
            moment().format("YYYYMMDD") +
            "/" +
            nanoid(32) +
            `_w${img.width}_h${img.height}.` +
            file.file.name.split(".").slice(-1)[0];
          file.width = img.width;
          file.height = img.height;
          resolve(file);
        };
        img.src = objectUrl;
      } catch (e) {
        console.log(e);
        file.error = e;
        resolve(file);
      }
    }
  });
}

function isFunction(fn) {
  return (
    Object.prototype.toString.call(fn).toLowerCase().slice(-9, -1) ===
    "function"
  );
}

async function uploadFile(fileItem, callback) {
  return new Promise((resolve) => {
    ossInstance
      .big({
        /**
         * 注意这里的前缀, 各个项目使用时, 一定要根据环境修改
         */
        fileName: "/demo/" + fileItem.fileName,
        file: fileItem.file,
        name: "admalltech-public",
        callback(p) {
          if (p === 1) {
            fileItem.sucess = true;
            resolve(fileItem);
          }
          callback && isFunction(callback) && callback(fileItem, p);
        },
        meta: {},
      })
      .then(() => {})
      .catch((err) => {
        fileItem.error = err;
        resolve(fileItem);
      });
  });
}

async function upload(files, callback) {
  // 整理文件名
  let res = await Promise.all(files.map((item) => mapFileName(item)));
  // 压缩图片类文件
  res = await Promise.all(res.map((item) => compressImg(item)));

  // 上传文件
  res = await Promise.all(res.map((item) => uploadFile(item, callback)));
  return res;
}

function countSize(fileList) {
  return fileList.reduce((pv, nv) => {
    return pv + nv.file.size;
  }, 0);
}

ossInstance.countSize = countSize;
ossInstance.compressImg = compressImg;
ossInstance.mapFileName = mapFileName;
ossInstance.uploadFile = uploadFile;
ossInstance.upload = upload;

export default ossInstance;
/**
 * 此处是否需要挂载到Vue原型链上, 可根据实际情况决定
 */
Vue.prototype.$oss = ossInstance;