0

I just want to upload a .dat file from a windows phone to a php script.

This is my code, but doesn't work. Can anyone see a reason why?

C#:

string fileBase64 = "UklGRt4lAABXQVZFZm10IBAAAAABAAEARKw...";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://...mysite.../upload.php");
request.Method = "POST";
request.ContentType = "application/octet-stream";

string postData = String.Format("file={0}", fileBase64);   

// 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:

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


    if(isset($_POST['file']))
    {
        $base64_string = $_POST['file'];
        $ifp = fopen( UPLOAD_DIR.'aaa.dat', "wb" ); 
        fwrite( $ifp, base64_decode($base64_string) ); 
        fclose( $ifp ); 

        echo "ok";
        echo $base64_string;
        echo base64_decode($base64_string);

    }else{
            echo "no submit";
        }
drankin2112
  • 4,715
  • 1
  • 15
  • 20
xRobot
  • 25,579
  • 69
  • 184
  • 304
  • 2
    What do you mean by "doesn't work"? What happens? – drankin2112 Jan 22 '14 at 17:02
  • To echo the above comment, please describe the behavior you are seeing and any exceptions received. Also, why are you posting a base 64 string instead of the file contents directly if you're just saving the file out in the end? – lsuarez Jan 22 '14 at 17:08

1 Answers1

0

You’re abusing the HTTP protocol.

Here’s the correct way to upload files to the server. Be sure to read comments, and also you'll probably want to do this asynchronously. For the asynchronous path I'd suggest you try the new async-await feature of the C# language, it's very helpful for such tasks, compared to your Begin/End approach.

Community
  • 1
  • 1
Soonts
  • 20,079
  • 9
  • 57
  • 130