【问题标题】:How do I receive a file sent from WebClient.UploadFile()?如何接收从 WebClient.UploadFile() 发送的文件?
【发布时间】:2014-02-25 23:50:58
【问题描述】:

由于这个简单的测试有效(在正文中传递一个字符串):

服务器代码:

public string PostArgsAndFile([FromBody] string value, string serialNum, string siteNum)
{
    string s = string.Format("{0}-{1}-{2}", value, serialNum, siteNum);
    return s;
}

客户端代码:

private void ProcessRESTPostFileData(string uri)
{
    using (var client = new WebClient())
    {
        client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
        var data = "=Short test...";
        var result = client.UploadString(uri, "POST", data);
        MessageBox.Show(result);
    }
}

...然后我尝试更进一步(朝着我真正需要做的事情 - 发送文件,而不是字符串);我将服务器代码更改为:

public string PostArgsAndFile([FromBody] byte[] value, string serialNum, string siteNum)
{
    byte[] bite = value;
    string s = string.Format("{0}{1}{2}", value.ToString(), serialNum, siteNum);
    return s;
}

...和客户端代码:

using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    var result = client.UploadFile(uri, @"C:\MiscInWindows7\SampleXLS.csv");
}

...但是在运行时会死掉:

System.Net.WebException 未处理 H结果=-2146233079 Message=远程服务器返回错误:(415) Unsupported Media Type。

那么我怎样才能接收以这种方式上传的文件呢?我需要什么媒体类型,如何指定?

更新

由于我最终需要发送一个文件,或者至少是一个文件的内容,我找到了this SO Question/Answer并将我的代码更改为:

using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    StringBuilder sb = new StringBuilder();
    using (StreamReader sr = new StreamReader(@"C:\MiscInWindows7\SampleXLS.csv"))
    {
        String line;
        while ((line = sr.ReadLine()) != null)
        {
            sb.AppendLine(line);
        }
    }
    string allLines = sb.ToString();
    byte[] byteData = UTF8Encoding.UTF8.GetBytes(allLines);
    byte[] responseArray = client.UploadData(uri, byteData);

    // Decode and display the response.
    MessageBox.Show("\nResponse Received.The contents of the file uploaded are:\n{0}",
        System.Text.Encoding.ASCII.GetString(responseArray));
}

...虽然这表明 byteData 已正确分配给我,但似乎没有任何东西进入服务器 - 服务器的“值”属性:

public void PostArgsAndFile([FromBody] byte[] value, string serialNum, string siteNum)

...在调用方法时只是一个空字节数组。

我尝试删除 [FromBody],但无济于事(没有更改),并将其更改为 [FromUri](我认为这不起作用,但在百灵鸟上尝试过)导致它崩溃并出现 WebException .

那么如何让服务器接受/识别/接收字节数组呢?

【问题讨论】:

    标签: asp.net-web-api http-headers webclient system.net.webexception media-type


    【解决方案1】:

    这行得通:

    它本身并没有传递文件,也不是字面意思,而是传递了文件的内容,这对我来说已经足够了。如果客户端要创建一个xml文件,它只需要在发送之前将该文件序列化为一个字符串,如下所示:

    客户

    private void button1_Click(object sender, EventArgs e)
    {
        ProcessRESTPostXMLFileAsStr("http://Platypus:28642/api/Platypi/PostArgsAndXMLFileAsStr?serialNum=192837465&siteNum=42");
    }
    
    private void ProcessRESTPostXMLFileAsStr(string uri)
    {
        using (var client = new WebClient())
        {
            client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            StringBuilder sb = new StringBuilder();
            using (StreamReader sr = new StreamReader(@"C:\Platypus\eXtraneousMothLepidoptera.XML"))
            {
                String line;
                while ((line = sr.ReadLine()) != null)
                {
                    sb.AppendLine(line);
                }
            }
            // I don't know why the prepended equals sign is necessary, but it is
            string allLines = "=" + sb.ToString();
            var result = client.UploadString(uri, "POST", allLines);
            MessageBox.Show(result);
        }            
    }
    

    服务器(Web API 应用程序)

    [Route("api/Platypi/PostArgsAndXMLFileAsStr")]
    public void PostArgsAndXMLFileAsStr([FromBody] string stringifiedXML, string serialNum, string siteNum)
    {
        string s = string.Format("{0}{1}{2}", stringifiedXML, serialNum, siteNum);
        // Parsing the contents of the stringified XML left as an exercise to the exorcist
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-10
      • 2010-12-19
      • 2017-09-10
      • 2013-01-01
      相关资源
      最近更新 更多