简体   繁体   English

通过POST以文件上载/分段形式使用REST WebService

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

I have a REST webservice method created using Django, which processes/handles file upload. 我有一个使用Django创建的REST网络服务方法,该方法处理/处理文件上传。 How do I consume it from my windows-form/desktop application using C#? 如何使用C#从Windows窗体/桌面应用程序中使用它? In addition, can someone explain how can I do dictionary parameter passing in C#, like the below python snippet code? 另外,有人可以解释如何在C#中传递字典参数,例如下面的python代码段代码?

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

If you can use DNF45 then MultipartFormDataContent will do most of the heavy lifting for you. 如果可以使用DNF45,则MultipartFormDataContent将为您完成大部分繁重的工作。 The following sample uploads a photo to picpaste mimicking a form post. 以下示例将照片上传到模仿表单帖子的picpaste中。 Then it uses HtmlAgility to pick apart the response which is going a lot further than you asked but is a handy thing to be able to do when you have to use interactive web pages as though they were web services. 然后,它使用HtmlAgility来分离响应,响应比您要求的要远得多,但是当您必须像使用Web服务那样使用交互式网页时,这是一件很方便的事情。

Obviously you have to change the file name to point at a picture on your own computer. 显然,您必须更改文件名以指向您自己计算机上的图片。 This isn't supposed to be production grade, it was just me figuring out how to manipulate picpaste because I'm too cheap to pay for imgur. 这本不应该是生产级的,那只是我想出如何处理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();
      }
    }
  }
}

If the response is JSON rather than HTML, which is likely for a web service, use the Newtonsoft.Json parser. 如果响应是JSON而非HTML(Web服务可能使用的响应),请使用Newtonsoft.Json解析器。 There are tutorials all over the net. 网络上都有教程。 It's comprehensive and very fast, my weapon of choice. 它是全面且非常快捷的,我的选择武器。 Broadly, you create classes to model the object graph you are expecting in the JSON and then use them to type a generic method call. 广泛地讲,您可以创建类以对JSON中期望的对象图进行建模,然后使用它们键入通用方法调用。

using Newtonsoft.Json;

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

You can get both HtmlAgility and Newtonsoft.Json from NuGet. 您可以从NuGet获取HtmlAgility和Newtonsoft.Json。

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

相关问题 使用 Python 通过 POST 多部分表单数据上传文件 - Upload file via POST multipart form-data using Python 通过 POST 方法上传图片 multipart/form-data - Upload image multipart/form-data via POST method 如何使用 HTTP POST multipart/form-data 将文件上传到服务器? - How to upload file to server with HTTP POST multipart/form-data? 如何使用multipart / form-data post方法将对象的实例上传到服务器REST? - How to use multipart/form-data post method to upload an instance of an object to a server REST? 将文件从Flex上传到WCF REST Stream问题(如何在REST WS中解码多部分表单帖子) - Uploading file from Flex to WCF REST Stream issues (how to decode multipart form post in REST WS) 使用C#中的WebClient通过multipart-form-data上传文件 - File upload via multipart-form-data using WebClient in C# c# 如何使用 HTTP POST multipart/form-data 将文件上传到 ashx - c# How to upload file to ashx with HTTP POST multipart/form-data 将文件从Html表单(multipart / form-data)上传到WCF REST服务作为流而不流式传输整个表单的输入? - Upload file from Html form (multipart/form-data) to WCF REST service as a stream without streaming the whole form's inputs? 使用多部分/表单数据上传文件 - File upload using multipart/form-data HttpClient Post REST API 中的 C# 多部分表单数据 - C# Multipart form-data in HttpClient Post REST API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM