【Javascript】前端对文件进行md5计算再上传,以节省OSS云端存储空间

安装插件 browser-md5-file

browser-md5-file 用于计算文件md5,文档介绍较少,看看就能使用↓
在这里插入图片描述

使用例子

  1. 比如我用 el-upload 组件上传图片
 <el-upload
    action=""
    class="upload-box"
    :show-file-list="false"
    accept=".jpg,.jpeg,.png"
    :http-request="(rawFile:any) => uploadFileToOss(rawFile,index)"
  >
    <svg-icon name="upload" class="icon"></svg-icon>
  </el-upload>
  1. 对文件进行包装(这个主要看个人项目实际需要)
const uploadFileToOss = async (rawFile: any, index: number) => {
  const data = await uploadOss({
    name: rawFile.file.name,
    file: rawFile.file,
  });
  propsList.value[index][propsList.value[index].id] = data.url;
  ElMessage.success('上传成功');
};

  1. 上传文件到 OSS ,先处理文件——>获取签名——>最后上传到 oss
import BMF from 'browser-md5-file'; // 用于计算文件md5:https://www.npmjs.com/package/browser-md5-file

type File = any;
type OssConfig = {
  accessid: string | Blob;
  policy: string | Blob;
  signature: string | Blob;
  key: string | Blob;
  host: any;
};
type OnUploadProgress = (progressEvent: any) => void;

// 上传文件到OSS
export async function uploadOss(
  file: File,
  onUploadProgress?: OnUploadProgress,
  ossUrl?: string,
) {
  if (!file) {
    return null;
  }
  // 对文件进行md5计算,节省云端存储空间
  const bmf = new BMF();
  const md5 = await new Promise((resolve, reject) => {
    bmf.md5(
      file.file,
      (err: any, md5: string) => {
        if (err) {
          reject(err);
        }
        resolve(md5);
      },
      (progress: number) => {
        console.log('progress number:', progress);
      },
    );
  });
  const name = file.name;
  const suffix = name.substring(name.lastIndexOf('.'), name.length);
  // 文件路径: xxx/文件md5值.文件后缀
  const filePath = `xxx/${md5}${suffix}`;
  // 1.获取OSS签名
  let r = await getOssSignature(filePath, ossUrl);
  // 2.开始上传文件到OSS
  await uploadStart(file.file, r.data, onUploadProgress);
  return r.data;
}

// 获取OSS签名
async function getOssSignature(filePath: any, ossUrl: any) {
  ossUrl = ossUrl ? ossUrl : '/xxx/xxx';
  let res = await request({
    url: ossUrl,
    method: 'get',
    params: { filePath },
  });
  return res;
}

// 上传文件开始准备
async function uploadStart(
  file: File,
  ossConfig: OssConfig,
  onUploadProgress?: OnUploadProgress,
) {
  // 组装发送数据
  let formData = new FormData();
  formData.append('OSSAccessKeyId', ossConfig.accessid); // Bucket
  // 拥有者的Access
  // Key Id。
  formData.append('policy', ossConfig.policy); // policy规定了请求的表单域的合法性
  formData.append('signature', ossConfig.signature); // 根据Access Key
  // Secret和policy计算的签名信息,OSS验证该签名信息从而验证该Post请求的合法性
  // ---以上都是阿里的认证策略
  formData.append('key', ossConfig.key); // 文件名字,可设置路径
  formData.append('success_action_status', '200'); // 让服务端返回200,不然,默认会返回204
  formData.append('file', file); // 需要上传的文件 file
  let data = await request({
    url: ossConfig.host,
    method: 'post',
    data: formData,
    headers: { 'Content-Type': 'multipart/form-data' },
    onUploadProgress: onUploadProgress,
    withCredentials: false,
  });
  return data;
}
posted @ 2023-08-29 11:45  努力挣钱的小鑫  阅读(395)  评论(0编辑  收藏  举报