using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Threading;
namespace HttpUploadTest
{
class Program
{
//static string m_address = "http://localhost:50000";
static string m_address = "http://210.73.221.45:50000";
static void FileUpload(object m_fileNamePath)
{
DateTime start = DateTime.Now;
// 要上傳的文件
FileStream oFileStream = new FileStream(m_fileNamePath.ToString(), FileMode.Open, FileAccess.Read);
BinaryReader oBinaryReader = new BinaryReader(oFileStream);
// 根據uri創建HttpWebRequest對象
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(m_address));
httpReq.Method = "POST";
//對發送的數據不使用緩存
httpReq.AllowWriteStreamBuffering = false;
//設置獲得響應的超時時間(半小時)
httpReq.Timeout = 300000;
//httpReq.Timeout = 5000;
// httpReq.ReadWriteTimeout = 150000;
httpReq.KeepAlive = true;
httpReq.ProtocolVersion = HttpVersion.Version11;
httpReq.ContentType = "application/pdf";
long filelength = oFileStream.Length;
httpReq.SendChunked = true;
//在將 AllowWriteStreamBuffering 設置為 false 的情況下執行寫操作時,必須將 ContentLength 設置為非負數,或者將 SendChunked 設置為 true。
//每次上傳4k
int bufferLength = 4*1024;
byte[] buffer = new byte[bufferLength];
//已上傳的字節數
long offset = 0;
//開始上傳時間
DateTime startTime = DateTime.Now;
int size = oBinaryReader.Read(buffer, 0, bufferLength);
Stream postStream = httpReq.GetRequestStream();
while (size > 0)
{
postStream.Write(buffer, 0, size);
offset += size;
size = oBinaryReader.Read(buffer, 0, bufferLength);
//Console.Write(".");
}
//Console.WriteLine(".");
postStream.Flush();
postStream.Close();
//獲取服務器端的響應
WebResponse webRespon = httpReq.GetResponse();
Stream s = webRespon.GetResponseStream();
StreamReader sr = new StreamReader(s);
DateTime end = DateTime.Now;
TimeSpan ts = end - start;
//讀取服務器端返回的消息
String sReturnString = sr.ReadLine();
Console.WriteLine("retcode="+sReturnString+" 花費時間="+ts.TotalSeconds.ToString());
s.Close();
sr.Close();
}
static void Main(string[] args)
{
string filePath = "D:\\test";
string[] ary = Directory.GetFiles(filePath);
for (int i = 0; i < (int)ary.Count(); i++)
{
Thread oneProcess = new Thread(new ParameterizedThreadStart(FileUpload));
oneProcess.Priority = ThreadPriority.AboveNormal;
oneProcess.Start(ary[i]);
oneProcess.IsBackground = false;
}
}
}
}