Skip to content

Node环境下分片上传时计算Buffer的sha256哈希值有问题 #14

@MorningK

Description

@MorningK

读取分片和计算hash值

async function readFileAsBuffers(filePath: string) {
  const state = await stat(filePath);
  logger.info("read file buffer %s, %s", filePath, state.size);
  if (state.size > maxRawFileSize) {
    // 读取文件内容为 Buffer
    const readStream = fs.createReadStream(filePath, { highWaterMark: chunkSize });
    const buffers: Buffer[] = await readStream.toArray();
    return buffers;
  }
  const buffer = await readFile(filePath);
  return [buffer];
}

function computeBufferHash(buffer: Buffer, algorithm = "sha256", encoding = "hex") {
  return crypto
    .createHash(algorithm)
    .update(buffer)
    .digest(encoding as crypto.BinaryToTextEncoding);
}

需要手动覆盖计算的hash值,设置bodySha256参数


  const signer = new Signer(openApiRequestData, "up", hash ? { bodySha256: hash } : undefined);

  const credential = {
    accessKeyId: process.env.accessKeyId,
    secretKey: process.env.secretKey,
  };

  // sign
  signer.addAuthorization(credential);

  if (hash && hash !== openApiRequestData.headers["X-Content-Sha256"]) {
    logger.info(
      "X-Content-Sha256 not match %s, %s, %s",
      action,
      hash,
      openApiRequestData.headers["X-Content-Sha256"]
    );
    openApiRequestData.headers["X-Content-Sha256"] = hash;
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions