上傳檔案到web server

客戶傳送端如下–html

 <html>
     <head>
     </head>
     <body>
         <form action="upload.php" method="post" enctype="multipart/form-data">
             file : <input type="file" name="file" id="file"/><br/>
             <input type="submit" name="submit" value="upload"/>
         </form>
     </body>
</html>

Server接收端如下–upload.php

<?php
    if($_FILES["file"]["error"]>0){
        echo "Error.".$_FILES["file"]["error"];
    }
    else{
        echo "檔案名稱:".$_FILES["file"]["name"]."<br/>";
        echo "檔案類型:".$_FILES["file"]["type"]."<br/>";
        echo "檔案大小:".$_FILES["file"]["size"]."<br/>";
        echo "檔案暫存:".$_FILES["file"]["tmp_name"]."<br/>";
        if(!file_exists("../tmp")){
           mkdir("../tmp",0700);
        }
        if(file_exists("../tmp/".$_FILES["file"]["name"])){
           echo "檔案已存在<br/>";
        }
        else{
            move_uploaded_file($_FILES["file"]["tmp_name"], "../tmp/".$_FILES["file"]["name"]);
        }
    }
?>

客戶端 c#程式如下

string UploadFilesToRemoteUrl(string url, string file)
        {
            // Create a boundry
            string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

            // Create the web request
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
            httpWebRequest.Method = "POST";
            httpWebRequest.KeepAlive = true;
            httpWebRequest.AllowWriteStreamBuffering = false;

            httpWebRequest.Credentials =
                System.Net.CredentialCache.DefaultCredentials;

            // Get the boundry in bytes
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            // Get the header for the file upload
            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\";filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";

            // Add the filename to the header
            string header = string.Format(headerTemplate, "file", file);

            //convert the header to a byte array
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

            // Add all of the content up.
            httpWebRequest.ContentLength = new FileInfo(file).Length + headerbytes.Length + (boundarybytes.Length * 2) + 2;

            // Get the output stream
            Stream requestStream = httpWebRequest.GetRequestStream();

            // Write out the starting boundry
            requestStream.Write(boundarybytes, 0, boundarybytes.Length);

            // Write the header including the filename.
            requestStream.Write(headerbytes, 0, headerbytes.Length);

            // Open up a filestream.
            FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);

            // Use 10M for the buffer
            byte[] buffer = new byte[10*1024];

            int bytesRead = 0;
            // Loop through whole file uploading parts in a stream.
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                requestStream.Write(buffer, 0, bytesRead);
                requestStream.Flush();
            }

            boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

            // Write out the trailing boundry
            requestStream.Write(boundarybytes, 0, boundarybytes.Length);

            // Close the request and file stream
            requestStream.Close();
            fileStream.Close();

            WebResponse webResponse = httpWebRequest.GetResponse();

            Stream responseStream = webResponse.GetResponseStream();
            StreamReader responseReader = new StreamReader(responseStream);

            string responseString = responseReader.ReadToEnd();

            // Close response object.
            webResponse.Close();

            return responseString;
        }

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *