C# 如何简单地将通用文件上传到php?

C# 如何简单地将通用文件上传到php?,c#,windows-phone-7,windows-phone-8,windows-phone,C#,Windows Phone 7,Windows Phone 8,Windows Phone,我正在使用此代码上载存储在IsolatedStorage中的通用文件,但它不起作用: string Filename = "aaa.dat"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://(mysite)/upload.php"); request.Method = "POST"; request.ContentType = "multipart/form-data";

我正在使用此代码上载存储在IsolatedStorage中的通用文件,但它不起作用:

string Filename = "aaa.dat";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://(mysite)/upload.php");
        request.Method = "POST";
        request.ContentType = "multipart/form-data";
        string postData = String.Format("user_file", Filename);   

        // Getting the request stream.
        request.BeginGetRequestStream
            (result =>
            {
                // Sending the request.
                using (var requestStream = request.EndGetRequestStream(result))
                {
                    using (StreamWriter writer = new StreamWriter(requestStream))
                    {
                        writer.Write(postData);
                        writer.Flush();
                    }
                }

                // Getting the response.
                request.BeginGetResponse(responseResult =>
                {
                    var webResponse = request.EndGetResponse(responseResult);
                    using (var responseStream = webResponse.GetResponseStream())
                    {
                        using (var streamReader = new StreamReader(responseStream))
                        {
                            string srresult = streamReader.ReadToEnd();
                        }
                    }
                }, null);
            }, null);
这是我的php文件:

<?php

define("UPLOAD_DIR", "./uploads/");

if(isset($_POST['action']) and $_POST['action'] == 'upload')
{
    if(isset($_FILES['user_file']))
    {
        $file = $_FILES['user_file'];
        if($file['error'] == UPLOAD_ERR_OK and is_uploaded_file($file['tmp_name']))
        {
            move_uploaded_file($file['tmp_name'], UPLOAD_DIR.$file['name']);
            echo "ok";
        }
    }
}

?>


有人能告诉我为什么这段代码不起作用吗?

它不起作用,因为下面一行

string postData = String.Format("user_file", Filename);   
相当于

string postData = "user_file";
而实际的文件数据从未包含在请求中<代码>字符串。格式用于将变量包含到模式中,即:

string logMessage = String.Format("Uploading {0}", Filename);
将生成“上传aaa.dat”

如果您想实现这一目标,您必须:

  • 读取文件的内容
  • 符合多部分/表单数据的规则

为什么等同于此?我该如何解决?Thanks@xRobot我不知道是不是那么简单。NET有很多神奇的功能,但除非已经内置了生成多部分/表单数据请求的功能,否则您需要做的不仅仅是更改一行代码。例如,请参见。是否有其他上传文件的方法?@xRobot肯定有,但php可能不会将其视为上传文件。看看我刚才分享的链接是否适合你。