简体   繁体   English

使用 RestSharp 通过 POST 上传文件

[英]Upload a file via POST using RestSharp

I'm trying to simulate a simple multipart HTML form in C#.我正在尝试用 C# 模拟一个简单的多部分 HTML 表单。

I was successful posting text as parameters using the addParameter function.我使用addParameter函数成功地将文本作为参数发布。 Now I want to upload a file using POST.现在我想使用 POST 上传文件。 I tried using the addFile function of the RestRequest object.我尝试使用RestRequest对象的addFile函数。 But it did not work!但它没有用! I'm getting response code: 0.我收到响应代码:0。

Here's my code:这是我的代码:

//preparing RestRequest by adding server url, parameteres and files...
RestRequest request = new RestRequest("http://" + ipTextBox.Text + "/samplepost/postdata.php", Method.POST);

request.AddParameter("msgpost", msgTextBox.Text);
request.AddFile("file1", "NEVER.jpg");

//calling server with restClient
RestClient restClient = new RestClient();
restClient.ExecuteAsync(request, (response) =>
{
     if (response.StatusCode == HttpStatusCode.OK)
     {
          //POST successful
          MessageBox.Show("Success!");                   
     }
     else
     {
          //error ocured during POST
          MessageBox.Show(":-(\nFailed.\nError: " + response.ErrorMessage);
     }
});

Please help me find mistakes in my code.请帮我找出代码中的错误。 Thanks in advance!提前致谢!

Is NEVER.jpg in the same location as the exe? NEVER.jpg 是否与 exe 位于同一位置? Because the way you're calling AddFile assumes it is.因为您调用 AddFile 的方式假定它是。

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

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