簡體   English   中英

CSharp - 如何使用 HTTP 請求和 Multipart 作為 Content-Type 上傳圖像

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

我正在使用 C# 4.7.2 並且正在使用控制台而不是 WinForms。 我正在嘗試獲取用戶圖像路徑的輸入,然后將發布請求發送到 ShareX Image Hoster API。

如何使用void保持簡單明了? 前任:

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

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$"
}

使用 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

那么rest這些headers后面就是未知ascii字節的廢話了。

回應是:

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

更新-.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
        }
    }
}

以下是.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
        }
    }

過程與.Net框架類似,只是可以使用System.IO進行文件操作。

更多信息

快速窺探 SO 會發現許多類似的問題以及類似的解決方案或實用的建議。 此答案專門用於使用 OPs ShareX 配置,但如果您需要更多信息,請閱讀以下文章:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM