简体   繁体   English

Multipart Form数据上传到HTTP服务器带参数

[英]Multipart Form Data Upload to HTTP server with parameters

I have an HTTP server that supports multipart form upload of files.我有一个 HTTP 服务器,支持文件的多部分上传。 The working curl request looks like工作 curl 请求看起来像

curl  -v --location --request POST 'http://192.168.1.3:9876/storage/module' \
--form 'name="I0000000001"' \
--form 'type="Log"' \
--form 'version="1.0.0.1"' \
--form 'user="admin"' \
--form 'file=@"/tmp/logDump.tgz"'

But I'm not able to convert this to C# successfully.但我无法将其成功转换为 C#。 The server is throwing HTTP 500 since the parameters ( name , version , type , and user ) are missing when sending with C#. I'm able to make this same file upload work in Curl, Python and C++, so it is not an issue with the server, but with my C# code.服务器抛出 HTTP 500,因为在使用 C# 发送时缺少参数( nameversiontypeuser )。我能够使相同的文件上传在 Curl、Python 和 C++ 中工作,所以这不是问题使用服务器,但使用我的 C# 代码。

string filePath = @"/tmp/logDump.tgz";
using (var httpClient = new HttpClient())
{
    using (var form = new MultipartFormDataContent())
    {
        using (var fs = File.OpenRead(filePath))
        {
            using (var streamContent = new StreamContent(fs))
            {
                using (var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync()))
                {
                    fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");

                    form.Add(fileContent, "file", Path.GetFileName(filePath));
                    form.Add(new System.Net.Http.MultipartContent("SIM00000001"), "name");
                    form.Add(new System.Net.Http.MultipartContent("Log"), "type");
                    form.Add(new System.Net.Http.MultipartContent("1.0.0.135"), "version");
                    form.Add(new System.Net.Http.MultipartContent("admin"), "user");
                    HttpResponseMessage response = await httpClient.PostAsync("http://192.168.1.3:9876/storage/module", form);
                    response.EnsureSuccessStatusCode();
                    Console.WriteLine($" result is {response.StatusCode}");
                }
            }
        }
    }
}

How to do this correctly?如何正确地做到这一点?

The multipart form data should be sent as just key-value pairs, replace the below lines,多部分表单数据应仅作为键值对发送,替换以下行,

 form.Add(new System.Net.Http.MultipartContent("SIM00000001"), "name");
 ...

to,到,

 form.Add(new StringContent("SIM00000001"), "name");
 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM