1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
public static string UploadFileEx(string uploadfile, string url)
{
Uri uri = new Uri(url);
string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create(uri);
wreq.ContentType = "multipart/form-data; boundary=" + boundary;
wreq.Method = "POST";
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"fichier\"; filename=\"" + Path.GetFileName(uploadfile) + "\"");
sb.Append("\r\n");
sb.Append("Content-Type: multipart/form-data");
sb.Append("\r\n");
sb.Append("\r\n");
string postHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n" + "--" + boundary + "\r\n");
FileStream fileStream = new FileStream(uploadfile, FileMode.Open, FileAccess.Read);
long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
wreq.ContentLength = length;
Stream requestStream = wreq.GetRequestStream();
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
byte[] buffer = new Byte[Convert.ToUInt32(Math.Min(4096, Convert.ToInt32(fileStream.Length)))];
int bytesRead = 0;
while ( (bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0 )
requestStream.Write(buffer, 0, bytesRead);
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
WebResponse responce = wreq.GetResponse();
Stream s = responce.GetResponseStream();
StreamReader sr = new StreamReader(s);
string result = sr.ReadToEnd();
wreq.Close();
requestStream.Close();
return result;
} |
Partager