简体   繁体   English

CSharp - 如何使用 HTTP 请求和 Multipart 作为 Content-Type 上传图像

[英]CSharp - How can I upload an image using a HTTP Request and Multipart as the Content-Type

I am using C# 4.7.2 and am using a Console and not WinForms.我正在使用 C# 4.7.2 并且正在使用控制台而不是 WinForms。 I am trying to get an input of a user's image path then send a post request to a ShareX Image Hoster API.我正在尝试获取用户图像路径的输入,然后将发布请求发送到 ShareX Image Hoster API。

How can I keep it plain and simple using void ?如何使用void保持简单明了? EX:前任:

public static void UploadImg(string ImagePath, string UploadAPI, string UploadKey) { }

ShareX Config: ShareX 配置:

{
    "Version": "13.2.1",
    "Name": "host",
    "DestinationType": "ImageUploader",
    "RequestMethod": "POST",
    "RequestURL": "https://ADDRESS/upload",
    "Headers": {
        "token": "name_RANDOMSTRING",
        "json": "true"
    },
    "Body": "MultipartFormData",
    "Arguments": {
        "imgfile": null
    },
    "FileFormName": "imgfile",
    "URL": "$json:url$"
}

Capturing traffic with Fiddler I can use these headers:使用 Fiddler 捕获流量我可以使用这些标头:

POST https://IMAGEHOST/api/upload HTTP/1.1
token: SPECIALKEY
json: true
Content-Type: multipart/form-data; boundary=--------------------8d8ee229124e662
User-Agent: ShareX/13.4.0
Host: IMGHOSTER
Content-Length: 7518
Connection: Keep-Alive

----------------------8d8ee229124e662
Content-Disposition: form-data; name="imgfile"; filename="851TO25E8.png"
Content-Type: image/png

Then the rest after these headers is unknown ascii bytes nonsense.那么rest这些headers后面就是未知ascii字节的废话了。

The response is:回应是:

{"url":"https://FinalShortenedURL/‌​​​‌‌​‌​‌‌​‌‌‌‌‌‌​​​‌​‌‌‌​​​​​‌​‌​‌‌‌‌‌​​‌‌‌‌​​‌‌‌‌​‌‌‌‌‌​​"}

UPDATE -.Net 4.7.2更新-.Net 4.7.2

public static async Task UploadImg(string ImagePath, string UploadAPI, string UploadKey)
{
    using (var client = new System.Net.Http.HttpClient())
    {
        // TODO: implement auth - this example works for bearer tokens:
        // client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", UploadKey);
        // Or you could use simple headers:
        client.DefaultRequestHeaders.Add("token", UploadKey);
        // inject the JSON header... and others if you need them
        client.DefaultRequestHeaders.Add("json", "true");

        var uri = new System.Uri(UploadAPI);

        // Load the file:
        var file = new System.IO.FileInfo(ImagePath);
        if (!file.Exists)
            throw new ArgumentException($"Unable to access file at: {ImagePath}", nameof(ImagePath));

        using (var stream = file.OpenRead())
        {
            var multipartContent = new System.Net.Http.MultipartFormDataContent();
            multipartContent.Add(
                new System.Net.Http.StreamContent(stream),
                "imgfile", // this is the name of FormData field
                file.Name);

            System.Net.Http.HttpRequestMessage request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, uri);
            request.Content = multipartContent;
            var response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode(); // this throws an exception on non HTTP success codes
        }
    }
}

The following is the original posted solution for.Net Core to upload using multi-part:以下是.Net Core使用多部分上传的原贴解决方案:

    public static async Task UploadImg(string ImagePath, string UploadAPI, string UploadKey)
    {
        using (var client = new Windows.Web.Http.HttpClient())
        {
            // TODO: implement auth - this example works for bearer tokens:
            client.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Bearer", UploadKey);
            // Or you could use simple headers:
            client.DefaultRequestHeaders.Add("token", UploadKey);

            // Load the file:
            StorageFile file = await StorageFile.GetFileFromPathAsync(ImagePath);

            var uri = new System.Uri(UploadAPI);

            HttpMultipartFormDataContent multipartContent = new HttpMultipartFormDataContent();

            multipartContent.Add(
                new HttpStreamContent(stream),
                "imgfile", // this is the name of FormData field
                file.Name);

            Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, uri);
            request.Content = multipartContent;
            var response = await client.SendRequestAsync(request);
            response.EnsureSuccessStatusCode(); // this throws an exception on non HTTP success codes
        }
    }

The process is similar in.Net framework, except that you can use System.IO for file operations.过程与.Net框架类似,只是可以使用System.IO进行文件操作。

More Information更多信息

Having a quick snoop around SO will find many similar questions with similar solutions or pratical advice.快速窥探 SO 会发现许多类似的问题以及类似的解决方案或实用的建议。 This answer is specifically provided to work with OPs ShareX configuration, but if you need further information have a read over these articles:此答案专门用于使用 OPs ShareX 配置,但如果您需要更多信息,请阅读以下文章:

暂无
暂无

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

相关问题 如何使用Content-Type:multipart / form-data通过Web API请求主体参数访问? - How request body parameter access by Web API using Content-Type: multipart/form-data? 如何在 http 请求中指定预期的响应内容类型? - How to specify the expected response content-type in a http request? 如何将 Content-Type 添加到 http 发布方法的 header 中? - How can I add Content-Type to header of http post method? 如何在 ASP.NET MVC 中使用 GET 请求发送 Content-Type 标头? - How can I send Content-Type header with a GET request in ASP.NET MVC? 批处理请求必须具有“ Content-Type”标头/“ multipart / mixed”作为媒体类型 - The batch request must have a “Content-Type” header / “multipart/mixed” as the media type 我们如何在下载/上传 dropbbox 方法中获取文件 mime-type/content-type? - How can we get files mime-type/content-type in download/upload dropbbox methods? 验证请求内容类型 - Validating Request Content-Type 如何在我对Get请求的响应中使用c#创建multipart / form-data类型的内容 - How do I create the content of type multipart/form-data using c# as part of my response to Get request 在.NET MVC 4(Web API)中,如何拦截控制器请求并更改其内容类型? - In .NET MVC 4 (Web API), how do I intercept a request for a controller and change it's Content-Type? 在 C# 中发出 post 请求时如何指定 content-type? - How do I specify the content-type when making a post request in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM