
// 提取Base64数据部分
function extractBase64Data(base64String) {
  const parts = base64String.split(';base64,');
  return parts.length > 1 ? parts[1] : base64String;
}



// 核心转换方法
export function  convertToFile(base64Input,fileName) {
    let fileObject = null

  try {
    // 提取MIME类型
    let mimeType = 'application/octet-stream';
    if (base64Input.startsWith('data:')) {
        console.log('base流')
        const mimeMatch = base64Input.match(/^data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+);base64,/);
        if (mimeMatch && mimeMatch[1] ) {
            mimeType = mimeMatch[1];
            console.log('替换匹配内容',mimeType)
        }
    }
    // 提取纯Base64数据
    const base64Data = extractBase64Data(base64Input);
    
    // 解码Base64
    const byteCharacters = atob(base64Data);
    const byteArrays = [];
    
    // 分块处理大文件
    for (let offset = 0; offset < byteCharacters.length; offset += 1024) {
      const slice = byteCharacters.slice(offset, offset + 1024);
      const byteNumbers = new Array(slice.length);
      
      for (let i = 0; i < slice.length; i++) {
        byteNumbers[i] = slice.charCodeAt(i);
      }
      
      byteArrays.push(new Uint8Array(byteNumbers));
    }

    // 创建Blob并转换为File对象
    const blob = new Blob(byteArrays, { type: mimeType });
    fileObject = new File([blob], fileName, { 
      type: blob.type,
      lastModified: Date.now()
    });

    console.log('转换成功！',fileObject)

  } catch (error) {
    console.error('转换失败:', error);
    console.log('转换失败')
  }

  return fileObject
}



