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

Postman上传文件致Azure函数上传SharePoint文件损坏的解决方法

解决Azure函数中通过HTTP上传文件到SharePoint时文件损坏的问题

问题根源

当你通过Postman以multipart/form-data形式提交文件时,HTTP请求的Body并非纯文件字节流,而是包含了分隔边界符、Content-Disposition头部等额外内容。直接读取request.Body会把这些无关内容一并上传,导致文件字节数变大,最终损坏无法打开。

解决方案

根据你Postman的提交方式,选择对应处理方案:

方案1:解析Multipart请求(推荐,兼容form-data提交)

如果用Postman的form-data选项上传文件,需要在Azure函数中解析multipart内容,提取出原始文件流:

[Function(nameof(DocumentUploader))]
public async Task<HttpResponseData?> UploadAsync(
    [HttpTrigger(AuthorizationLevel.Function, "post", Route = $"{nameof(DocumentUploader)}/{{filename}}/{{extension}}")]
    HttpRequestData request,
    string filename,
    string extension)
{
    // 检查是否为multipart请求
    var contentType = request.Headers.GetValues("Content-Type").FirstOrDefault();
    if (!string.IsNullOrEmpty(contentType) && contentType.StartsWith("multipart/"))
    {
        using var reader = new MultipartReader(contentType, request.Body);
        MultipartSection section;
        while ((section = await reader.ReadNextSectionAsync()) != null)
        {
            // 找到包含文件名的section(即文件内容)
            if (!string.IsNullOrEmpty(section.ContentDisposition?.FileName))
            {
                // 使用section.Body作为原始文件流上传
                await UploadToSharePoint(section.Body, filename, extension);
                return request.CreateResponse(HttpStatusCode.OK);
            }
        }
    }

    return request.CreateResponse(HttpStatusCode.BadRequest, "未找到有效文件");
}

// 你的Graph API上传方法
private async Task UploadToSharePoint(Stream fileStream, string filename, string extension)
{
    // 原有上传逻辑,注意确保读取流时从起始位置开始
    fileStream.Position = 0;
    // ... 调用Graph API上传
}

方案2:使用Binary模式提交文件

如果Postman改用Binary选项上传文件,需设置请求的Content-Type为对应文档类型(比如.docx用application/vnd.openxmlformats-officedocument.wordprocessingml.document,或通用的application/octet-stream),此时request.Body就是纯文件流,但需要确保读取流前重置位置:

[Function(nameof(DocumentUploader))]
public async Task<HttpResponseData?> UploadAsync(
    [HttpTrigger(AuthorizationLevel.Function, "post", Route = $"{nameof(DocumentUploader)}/{{filename}}/{{extension}}")]
    HttpRequestData request,
    string filename,
    string extension)
{
    // 重置流位置到起始点
    request.Body.Position = 0;
    // 直接使用request.Body上传
    await UploadToSharePoint(request.Body, filename, extension);
    return request.CreateResponse(HttpStatusCode.OK);
}

关键注意事项

  • 无论哪种方案,上传前务必确保流的Position为0,避免从中间位置读取导致内容缺失。
  • Postman提交时,不要在请求中添加额外的参数或格式编码,确保文件内容未被修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 00:01:40