Home of Testers Forum Index Home of Testers
Nothing else, only testing!
Welcome to our Classroom!
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

Upload a file via HTTP post

 
Post new topic   Reply to topic    Home of Testers Forum Index -> Testers' Weapons - C#
View previous topic :: View next topic  
Author Message
BigPanda



Joined: 29 May 2008
Posts: 50

PostPosted: Tue Nov 18, 2008 1:04 am    Post subject: Upload a file via HTTP post Reply with quote

Code:
public void WebRequestUploadSuccessTest()
        {
            // Setup user params
            string VideoFile = @"f:\vids\testvideo.avi";

            // Setup soap classes
            Authentication auth = new Authentication();
            auth.Url = "https://services.nirvanix.com/ws/Authentication.asmx";
            IMFS imfs = new IMFS();
            imfs.Url = "http://services.nirvanix.com/ws/IMFS.asmx";

            // Login and get sessionToken
            string sessionToken = auth.Login(appKey, Username, Password);
            // Get the upload node
            UploadNode node = imfs.GetUploadNode(sessionToken, new FileInfo(VideoFile).Length);
            // Format the URL with
            string url = "http://" + node.IPAddress + "/Upload.ashx?uploadToken=" + node.AccessToken + "&destFolderPath=/httpupload/";

            string response = UploadFilesToRemoteUrl(url, VideoFile);

            Console.Write(response);
        }

        /// <summary>
        /// A method to upload files to the remote server streaming.
        /// </summary>
        private 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.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 4096 for the buffer
            byte[] buffer = new byte[4096];

            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;
        }
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    Home of Testers Forum Index -> Testers' Weapons - C# All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group