簡體   English   中英

通過POST以文件上載/分段形式使用REST WebService

[英]Consuming REST WebService via POST with file upload/multipart form

我有一個使用Django創建的REST網絡服務方法,該方法處理/處理文件上傳。 如何使用C#從Windows窗體/桌面應用程序中使用它? 另外,有人可以解釋如何在C#中傳遞字典參數,例如下面的python代碼段代碼?

import requests
url = "http://<url>
files = {'file' : open("<filename>", "rb").read(), 'name':'sample.txt'}
r = requests.post(url, files)

如果可以使用DNF45,則MultipartFormDataContent將為您完成大部分繁重的工作。 以下示例將照片上傳到模仿表單帖子的picpaste中。 然后,它使用HtmlAgility來分離響應,響應比您要求的要遠得多,但是當您必須像使用Web服務那樣使用交互式網頁時,這是一件很方便的事情。

顯然,您必須更改文件名以指向您自己計算機上的圖片。 這本不應該是生產級的,那只是我想出如何處理picpaste的方法,因為我太便宜了,無法購買imgur。

using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mime;

namespace picpaste1
{
  class Program
  {
    static void Main(string[] args)
    {
      var fi = new FileInfo(@"path\to\picture.png");
      using (var client = new HttpClient())
      using (var mfdc = new MultipartFormDataContent())
      using (var filestream = fi.OpenRead())
      using (var filecontent = new StreamContent(filestream))
      {

        filecontent.Headers.ContentDisposition = 
          new ContentDispositionHeaderValue(DispositionTypeNames.Attachment)
        {
          FileName = fi.Name,
          Name = "upload"
        };
        filecontent.Headers.ContentType = new MediaTypeHeaderValue("image/png");

        mfdc.Add(new StringContent("7168000"), "MAX_FILE_SIZE");
        mfdc.Add(filecontent);
        mfdc.Add(new StringContent("9"), "storetime");
        mfdc.Add(new StringContent("no"), "addprivacy");
        mfdc.Add(new StringContent("yes"), "rules");
        var uri = "http://picpaste.com/upload.php";
        var res = client.PostAsync(uri, mfdc).Result;
        var doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(res.Content.ReadAsStringAsync().Result);
        uri = doc.DocumentNode.SelectNodes("//td/a").First()
          .GetAttributeValue("href","NOT FOUND");
        res = client.GetAsync(uri).Result;
        doc.LoadHtml(res.Content.ReadAsStringAsync().Result);
        var foo = doc.DocumentNode.SelectNodes("//div[@class='picture']/a").First()
          .GetAttributeValue("href","NOT FOUND");
        Console.WriteLine("http://picpaste.com{0}", foo);
        Console.ReadLine();
      }
    }
  }
}

如果響應是JSON而非HTML(Web服務可能使用的響應),請使用Newtonsoft.Json解析器。 網絡上都有教程。 它是全面且非常快捷的,我的選擇武器。 廣泛地講,您可以創建類以對JSON中期望的對象圖進行建模,然后使用它們鍵入通用方法調用。

using Newtonsoft.Json;

var res = client.PostAsync(uri, mfdc).Result;
Foo foo = JsonConvert.DeserializeObject<Foo>(res.Content.ReadAsStringAsync().Result);

您可以從NuGet獲取HtmlAgility和Newtonsoft.Json。

暫無
暫無

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

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