StreamContent 不占用流的长度

StreamContent doesn't take the length of the stream

我正在与 Dropbox 交互,我通过它的路径获取一个文件,将其作为流读出,将该流的内容复制到文件流中并使用该文件流创建一个 StreamContent 对象,我可以将其附加到我的multipart/form-data:

[FunctionName("SendFiles")]
        public static async Task<HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestMessage req,
            ILogger log)
{
    ...
    DropboxClient dropbox = new DropboxClient("token");

    MultipartFormDataContent formdata = new MultipartFormDataContent();
    string name = GetFileName(filePath);
    string tempfile = Path.GetTempFileName();
    string tempFilePath = getTempFilePath(tempfile, name);
    FileStream fs = File.Create(tempFilePath);
    using (var res = await dropbox.Files.DownloadAsync(filePath))
    {
          (await res.GetContentAsStreamAsync()).CopyTo(fs);
    }

    HttpContent content = new StreamContent(fs);

    content.Headers.Add("Content-Type", GetFileType(name));
    formdata.Add(content, "files", name);
    // System.IO.File.Delete(tempfile); at this point, we still are using the file for some reason and so I can't delete it
    // rest of the method, sending the content using httpClient
...
}

private static string getTempFilePath(string tempfile, string name)
{
    char[] charSeparators = new char[] { '\' };
    var splitPath = tempfile.Split(charSeparators);
    splitPath[splitPath.Length - 1] = name;
    return String.Join("\", splitPath);
}

private static string GetFileName(string path)
{
    char[] charSeparators = new char[] { '/' };
    var splitPath = path.Split(charSeparators);
    return splitPath[splitPath.Length - 1];
}

private static string GetFileType(string name)
{
    char[] charSeparators = new char[] { '.' };
    var splitName = name.Split(charSeparators);
    string extension = splitName[1].ToLower();
    switch (extension)
    {
        case "pdf":
              return "application/pdf";
        case "png":
              return "image/png";
        case "doc":
              return "application/msword";
        case "docx":
              return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        case "txt":
             return "text/plain";
        case "tif":
             return "image/tif";
        case "jpg":
            return "image/jpg";
        case "rtf":
            return "application/rtf";
        // default == not supported type, we don't set content type
        default:
            return "";
     }
}

当我调试时,我可以清楚地看到在复制到文件流时流的长度得到了更新,但是当我随后使用文件流创建流内容时,内容的长度仍然为 0。这是怎么回事发生了什么,我该怎么做才能解决这个问题?

您应该能够像这样将来自保管箱客户端的流直接馈送到 StreamContent 中:

HttpContent content = new StreamContent(await res.GetContentAsStreamAsync());