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

时间:2014-01-21 14:53:54

标签: 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";
        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";
        }
    }
}

?>

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

1 个答案:

答案 0 :(得分:1)

它不起作用,因为以下行

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

相当于

string postData = "user_file";

实际的文件数据永远不会包含在请求中。 String.Format用于将变量包含到模式中,即:

string logMessage = String.Format("Uploading {0}", Filename);

会生成“正在上传aaa.dat”。

如果你想做这项工作,你将不得不:

  • 阅读文件内容
  • 符合multipart / form-data RFC1867
  • 的规则