You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure File Storage文件上传问题:await失效与文件损坏

Azure文件存储上传问题修复方案

问题1:uploadStream未被正确等待导致方法提前退出

submitData是异步函数,返回Promise对象,若调用该方法的代码未用await或.then()处理,就会出现方法提前退出的情况。

修复方式:
确保调用submitData时使用await:

// 调用示例
await submitData(context, fileName, ext, base64, contentType, classification, upload);

若处于无法使用await的环境,可改用.then()链式处理:

submitData(context, fileName, ext, base64, contentType, classification, upload)
  .then(success => {
    // 处理成功逻辑
  })
  .catch(err => {
    // 处理错误
  });

同时建议给uploadStream添加错误捕获,避免未处理的Promise拒绝导致程序异常:

try {
  await client.uploadStream(readable, buffer.length, 4 * 1024 * 1024, 5, options);
  console.log("Upload successful");
} catch (err) {
  console.error("Upload failed:", err);
  throw err; // 抛出错误让调用方处理
}

问题2:上传文件损坏,内容为带$content-type的JSON格式

从损坏文件内容判断,你传入的base64参数并非纯文件的base64编码字符串,而是包含元数据的JSON字符串(比如{"$content-type":"application/pdf","$content":"AAAAAAAAAAAAAA...AAAAA"}),直接用Buffer.from(base64, 'base64')会把整个JSON当作base64解码,导致内容错误。

修复方式:
先解析JSON字符串,提取真实的文件base64内容再转成Buffer:

// 解析JSON,取出真实的base64内容
const contentObj = JSON.parse(base64);
const realBase64 = contentObj.$content;
const buffer = Buffer.from(realBase64, 'base64');

若base64参数可能同时存在纯base64和JSON两种格式,可添加判断兼容两种场景:

let realBase64 = base64;
// 判断是否为JSON格式的base64
if (base64.startsWith('{')) {
  try {
    const contentObj = JSON.parse(base64);
    realBase64 = contentObj.$content;
  } catch (err) {
    // 解析失败,按纯base64处理
  }
}
const buffer = Buffer.from(realBase64, 'base64');

完整修复后的代码

import { FileUploadStreamOptions, ShareFileClient } from "@azure/storage-file-share";
import { Readable } from "readable-stream";

async submitData(context: ComponentFramework.Context<IInputs>, fileName: string, ext: string, base64: string, contentType: string, classification: string, upload: any) : Promise<boolean> {
  // 处理可能的JSON格式base64
  let realBase64 = base64;
  if (base64.startsWith('{')) {
    try {
      const contentObj = JSON.parse(base64);
      realBase64 = contentObj.$content;
    } catch (err) {
      console.warn("Failed to parse base64 JSON, using original string:", err);
    }
  }

  const buffer = Buffer.from(realBase64, 'base64');
  const client = new ShareFileClient(upload.url);
  const readable = Readable.from(buffer);

  const options = {
    fileHttpHeaders: { 
      fileContentType: contentType,
    },
  };

  try {
    await client.uploadStream(readable, buffer.length, 4 * 1024 * 1024, 5, options);
    console.log("Upload successful");
  } catch (err) {
    console.error("Upload failed:", err);
    throw err;
  }
  
  // more logic
  return true;
}

内容的提问来源于stack exchange,提问作者Pablo Higueros

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 00:45:01