(共556篇)
全部分类

OSS上传文件前常用的处理函数(适用于普通PC)
[ 未分类 ] 

压缩文件

 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

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("compressImg()->a:", a);
        const blob = new Blob([a.target.result]);
        console.log("compressImg()->blob:", 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("compressImg()->catch", e);
      file.error = e;
      resolve(file);
    }
  });
}

图片文件添加尺寸后缀

 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
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("mapFileName()->file.file.name:", file.file.name);
        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(
            "mapFileName()->imgSize:",
            `_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("mapFileName()->catch:", e);
        file.error = e;
        resolve(file);
      }
    }
  });
}