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

上传文件均被识别为application/octet-stream的问题求助

问题解决:RestSharp上传文件ContentType始终为application/octet-stream

问题根源

  1. 全局设置Content-Type头错误:文件上传请求的整体Content-Type应为multipart/form-data,RestSharp会自动处理该请求头,手动设置为image/jpeg会破坏请求结构,且无法针对单个文件指定类型。
  2. AddFile默认重载未指定文件ContentType:RestSharp的默认AddFile方法不会自动识别文件MIME类型,默认使用application/octet-stream。

解决步骤

1. 添加MIME类型识别辅助方法

根据文件扩展名自动匹配对应MIME类型,覆盖常见的图片、视频、音频格式:

private string GetMimeType(string filePath)
{
    var extension = Path.GetExtension(filePath).ToLowerInvariant();
    return extension switch
    {
        ".jpg" or ".jpeg" => "image/jpeg",
        ".png" => "image/png",
        ".gif" => "image/gif",
        ".bmp" => "image/bmp",
        ".mp4" => "video/mp4",
        ".avi" => "video/x-msvideo",
        ".mp3" => "audio/mpeg",
        ".wav" => "audio/wav",
        // 按需添加更多扩展名对应的MIME类型
        _ => "application/octet-stream"
    };
}

2. 修改文件上传代码

移除全局Content-Type头,使用AddFile的重载版本指定单个文件的ContentType:

private void button1_Click(object sender, EventArgs e)
{
    if (filepaths != null)
    {
        var client = new RestClient("http://localhost:7071/api/function1");
        var request = new RestRequest(Method.Post);
        // 获取当前文件的MIME类型
        var fileMimeType = GetMimeType(filepaths);
        // 上传文件时指定ContentType
        request.AddFile("File", filepaths, fileMimeType);
        RestResponse response = client.Execute(request);
        Console.WriteLine(response.Content);
    }
}

3. 额外优化

  • 移除OpenFileDialog中冗余的FilterIndex设置(默认值即为0)。
  • 可以在选择文件后直接获取并存储MIME类型,避免上传时重复计算:
private void button2_Click(object sender, EventArgs e)
{
    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    openFileDialog1.Title = "Select File";
    openFileDialog1.InitialDirectory = @"C:\";
    openFileDialog1.Filter = "All files (*.*)|*.*";
    openFileDialog1.Multiselect = false;
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        textBox1.Text = openFileDialog1.FileName;
        filepaths = openFileDialog1.FileName;
        // 提前获取并存储文件MIME类型
        filetype = GetMimeType(filepaths);
    }
    else
    {
        textBox1.Text = "Please select a file!";
    }
}

此时上传时直接使用已存储的filetype即可:

request.AddFile("File", filepaths, filetype);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 04:54:23