简体   繁体   English

C#发布类似curl.exe的上传文件“ -F

[英]C# post upload file like curl.exe" -F

I'm trying to duplicate the following curl functionality in C# but to no avail. 我试图在C#中复制以下curl功能,但无济于事。 I get a bad request returned with the C# code. 我收到一个带有C#代码的错误请求。 The .NET code needs to replicate the curl file attachment/upload functionality. .NET代码需要复制curl文件的附件/上传功能。 I would appreciate help. 我将不胜感激。

"curl.exe" -F "attachment=@c:\\data\\img.jpg" "example.com" “ curl.exe” -F“ attachment = @ c:\\ data \\ img.jpg”“ example.com”

    public static async void Post(string fileName)
    {
        string url = "example.com";
        var stream = new FileStream(fileName, FileMode.Open);
        string name = Path.GetFileName(fileName);

        var client = new HttpClient { Timeout = TimeSpan.FromMinutes(10) };

        var streamContent = new StreamContent(stream);
        streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
        streamContent.Headers.ContentDisposition.Name = "\"file\"";
        streamContent.Headers.ContentDisposition.FileName = "\"" + name + "\"";
        streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

        var content = new MultipartFormDataContent { streamContent };
        HttpResponseMessage message = await client.PostAsync(url, content);
        string s = await message.Content.ReadAsStringAsync();
    }

fixed my issue. 解决了我的问题。 "attachment" needed to be the file. “附件”必须是文件。

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

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