Click here to Skip to main content
15,897,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello,
In web application i have to upload file to another site/server using api.
Please help to shortout this query..
below code gives "Operation has timeout error."

C#
if (FileUpload1.HasFile)
            {
                string path = Path.GetFullPath(FileUpload1.PostedFile.FileName);
                string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
                string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
                string fileLocation = Server.MapPath(@"~/upload/" + fileName);
           string URLAuth = "http://enterprise.smsgupshup.com/GatewayAPI/rest";
               
                FileUpload1.SaveAs(fileLocation);


                WebClient wbClient = new WebClient();
                NameValueCollection formData = new NameValueCollection();
                formData["method"] = "xlsUpload";
                formData["userid"] = "xxxxx";
                formData["password"] = "xxxxxx";
                formData["v"] = "1.1";
                formData["filetype"] = "xls";
                //formData["msg_type"] = "Text";
                formData["auth_scheme"] = "PLAIN";
                formData["xlsfile"] = fileLocation;

  UploadFilesToRemoteUrl(URLAuth, fileLocation, fileLocation, formData);
}

    public static void UploadFilesToRemoteUrl(string url, string files, string logpath, NameValueCollection nvc)
        {

            try
            {
                long length = 0;
                string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
                //string boundary = "ou812--------------8c405ee4e38917c";

                HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
                httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
                httpWebRequest2.Method = "POST";
                httpWebRequest2.KeepAlive = true;
                httpWebRequest2.Credentials = System.Net.CredentialCache.DefaultCredentials;


                Stream memStream = new System.IO.MemoryStream();
                byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

                string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

                foreach (string key in nvc.Keys)
                {
                    string formitem = string.Format(formdataTemplate, key, nvc[key]);
                    byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                    memStream.Write(formitembytes, 0, formitembytes.Length);
                }


                memStream.Write(boundarybytes, 0, boundarybytes.Length);

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

                string header = string.Format(headerTemplate, "uplTheFile", files);
                byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                memStream.Write(headerbytes, 0, headerbytes.Length);

                FileStream fileStream = new FileStream(files, FileMode.Open, FileAccess.Read);
                byte[] buffer = new byte[1024];

                int bytesRead = 0;

                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    memStream.Write(buffer, 0, bytesRead);
                    httpWebRequest2.MaximumResponseHeadersLength = 100000;
                    httpWebRequest2.ReadWriteTimeout = 200000;
                }
                memStream.Write(boundarybytes, 0, boundarybytes.Length);
                fileStream.Close();

                httpWebRequest2.ContentLength = memStream.Length;

                Stream requestStream = httpWebRequest2.GetRequestStream();
                memStream.Position = 0;

                byte[] tempBuffer = new byte[memStream.Length];
                memStream.Read(tempBuffer, 0, tempBuffer.Length);
                memStream.Close();

                requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                requestStream.Close();

                WebResponse webResponse2 = httpWebRequest2.GetResponse();
                Stream stream2 = webResponse2.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
                string s = (reader2.ReadToEnd());

                stream2.Flush();
                stream2.Close();
                requestStream.Flush();
                requestStream.Close();
                reader2.Close();
                webResponse2.Close();
                httpWebRequest2 = null;
                webResponse2 = null;
            }
            catch (Exception ex)
            {

            }
        }

}
Posted
Updated 27-Dec-12 20:17pm
v2

Kinjal,

You are recommended to use data driven request system, not direct by upload

insert request to data & run loop

C#
httpWebRequest2.MaximumResponseHeadersLength = 100000;
                    httpWebRequest2.ReadWriteTimeout = 200000;


you get set your own value

plz refer below given bulksms's api sample

Good Luck

C#
//================================================ C# Send Batch code sample ================================================//

/* We use the HttpUtility class from the System.Web namespace
*
* If you see of the error "'HttpUtility' is not declared", you are probably
* using a newer version of Visual Studio. You need to navigate to
* Project | <Project name> Properties | Application,
* and select e.g. ".NET Framework 4" instead of ".NET Framework 4 Client Profile" as your 'Target framework'.
*
* Next, visit Project | Add reference, and select "System.Web" (specifically
* System.Web - not System.Web.<something>).
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web;
using System.IO;


namespace C_Sharp_sendbatch
{
	class BatchSMS{

		public static string Post(string url, string data){
	
		string result = null;
		try{
			byte[] buffer = Encoding.Default.GetBytes(data);
			HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
			WebReq.Method = "POST";
			WebReq.ContentType = "application/x-www-form-urlencoded";
			WebReq.ContentLength = buffer.Length;
			Stream PostData = WebReq.GetRequestStream();
	
			PostData.Write(buffer, 0, buffer.Length);
			PostData.Close();
	
			HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
			Console.WriteLine(WebResp.StatusCode);
	
			Stream Response = WebResp.GetResponseStream();
			StreamReader _Response = new StreamReader(Response);
			result = _Response.ReadToEnd();
		}
		catch (Exception ex){
			Console.WriteLine(ex.Message);
		}
		return result.Trim() + "\n";
	}

        static void Main(string[] args){
		TextReader tr = new StreamReader(@"\Path\to\your\batch_file");
		// E.g. TextReader tr = new StreamReader(@"C:\Users\user\Desktop\my_batch_file.csv")
		// Please see http://bulksms.vsms.net/docs/eapi/submission/send_batch/ for information 
		// on what the format of your input file should be.

		string line;
		string batch = "";
		while ((line = tr.ReadLine()) != null){
			batch += line + "\n";
		}
		//Console.WriteLine(batch);
	
		tr.Close();
	
	
		string url = "http://bulksms.vsms.net:5567/eapi/submission/send_batch/1/1.0";
	
		/*****************************************************************************************************
		**Construct data
		*****************************************************************************************************/
		/*
		* Note the suggested encoding for the some parameters, notably
		* the username, password and especially the message.  ISO-8859-1
		* is essentially the character set that we use for message bodies,
		* with a few exceptions for e.g. Greek characters. For a full list,
		* see: http://bulksms.vsms.net/docs/eapi/submission/character_encoding/
		*/

		string data = "";
		data += "username=" + HttpUtility.UrlEncode("your_username", System.Text.Encoding.GetEncoding("ISO-8859-1"));
		data += "&password=" + HttpUtility.UrlEncode("your_password", System.Text.Encoding.GetEncoding("ISO-8859-1"));
		data += "&batch_data=" + HttpUtility.UrlEncode(batch, System.Text.Encoding.GetEncoding("ISO-8859-1"));
		data += "&want_report=1";
	
		string sms_result = Post(url, data);
	
		string[] parts = sms_result.Split('|');
	
		string statusCode = parts[0];
		string statusString = parts[1];
	
		if (!statusCode.Equals("0")){
			Console.WriteLine("Error: " + statusCode + ": " + statusString);
		}
		else{
			Console.WriteLine("Success: batch ID " + parts[2]);
		}
	
		Console.ReadLine();
        }
    }
}
 
Share this answer
 
v2

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