Click here to Skip to main content
16,005,491 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi !
I'm having an issue when trying to post a file to a php script.

I know 100% sure that the URL is correct and the php script is accessible. I know 100% that the file I'm trying to upload exists.

When I try and upload, the .GetResponse() method times out. Sometimes it throws the exception: "The underlying connection was closed: An unexpected error occurred on a receive"

Here's my file upload code:
C#
public static string PostData(string strUrl, string strFileToUpload)
{
    try
    {
        const string strFileFormName = "file";
        var oUri = new Uri(strUrl);
        var strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");

        // The trailing boundary string
        var boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n");

        // The post message header
        var sb = new StringBuilder();
        sb.Append("--");
        sb.Append(strBoundary);
        sb.Append("\r\n");
        sb.Append("Content-Disposition: form-data; name=\"");
        sb.Append(strFileFormName);
        sb.Append("\"; filename=\"");
        sb.Append(Path.GetFileName(strFileToUpload));
        sb.Append("\"");
        sb.Append("\r\n");
        sb.Append("Content-Type: ");
        sb.Append("application/octet-stream");
        sb.Append("\r\n");
        sb.Append("\r\n");
        var strPostHeader = sb.ToString();
        var postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);

        // The WebRequest
        var oWebrequest = (HttpWebRequest)WebRequest.Create(oUri);
        oWebrequest.ContentType = "multipart/form-data; boundary=" + strBoundary;
        oWebrequest.Method = "POST";
        oWebrequest.Timeout = Timeout.Infinite;
        oWebrequest.KeepAlive = true;
        // This is important, otherwise the whole file will be read to memory anyway...
        oWebrequest.AllowWriteStreamBuffering = true;

        // Get a FileStream and set the final properties of the WebRequest
        var oFileStream = new FileStream(strFileToUpload, FileMode.Open, FileAccess.Read);
        var length = postHeaderBytes.Length + oFileStream.Length + boundaryBytes.Length;
        oWebrequest.ContentLength = length;
        var oRequestStream = oWebrequest.GetRequestStream();

        // Write the post header
        oRequestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

        // Stream the file contents in small pieces (4096 bytes, max).
        //byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)oFileStream.Length))];
        var buffer = new Byte[checked((uint)oFileStream.Length)];
        var bytesRead = 0;
        while ((bytesRead = oFileStream.Read(buffer, 0, buffer.Length)) != 0)
            oRequestStream.Write(buffer, 0, bytesRead);
        oFileStream.Close();

        // Add the trailing boundary
        oRequestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
        var oWResponse = oWebrequest.GetResponse();
        var s = oWResponse.GetResponseStream();
        if (s != null)
        {
            var sr = new StreamReader(s);
            var sReturnString = sr.ReadToEnd();

            // Clean up
            oFileStream.Close();
            oRequestStream.Close();
            s.Close();
            sr.Close();

            return sReturnString;
        }
    }
  catch { return String.Empty; }
    return String.Empty;
}


here's my PHP code on the server end:
PHP
<?php
require('vars.php');
   $dbHost     = DB_HOST;		// MySQL host
   $dbUser     = DB_USER;	// MySQL username
   $dbPass     = DB_PASSWORD;	// MySQL password
   $dbDatabase = DB_NAME;	// MySQL database name
	function connect_database() {
		global $dbHost, $dbUser, $dbPass, $dbDatabase;
		$mysql = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
		if (!$mysql) {
			$html .= "Database Error".$header."Can not connect to database, please check the configuration.".$footer;
			die($html);
		}
		if (!mysql_select_db($dbDatabase, $mysql)) {
			mysql_close($mysql);
			$html .= "Database Error".$header."Can not select '".$dbDatabase."' database, please check the configuration.".$footer;
			die($html);
		}
		return $mysql;
	}
	connect_database();
			$ID = getRandomString();
			$Location = "stats/".$ID.".html";
			if(is_uploaded_file($_FILES['file']['tmp_name']))
			{
				if (move_uploaded_file($_FILES['file']['tmp_name'][0], $Location)) {
					mysql_query("INSERT INTO `user_stat_links` (`s_id`)VALUES('".$ID."')")
						or die(mysql_error());
					echo "http://myurl.com/stats/?id=".$ID;
					exit;
				}
			}
			echo "error";
?>


I'm extremely baffled by this. I've used this c# code before to upload files and it has worked 100% fine.

Please help!
Posted
Comments
Oliver Bleckmann 23-May-14 22:01pm    
This seems to be related to the server ("The underlying connection was closed"), maybe you hit some limits like script runtime or post request maximum size!? Go and check your php.ini. Eventually your POST is corrupted(due to encoding, length measurement issues) and PHP waits for more streaming data on the request (buffer underflow)!?

hope this helps.
Sergey Alexandrovich Kryukov 23-May-14 23:13pm    
Very likely so, I would say...
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900