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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
|
// the request header
HttpWebRequest imageShackWebRequest = WebRequest.Create("http://www.noelshack.com/api.php") as HttpWebRequest;
imageShackWebRequest.Method = "POST";
string fileName = "C:\\bac.jpg";
FileInfo fileToUploadInfo = new FileInfo(fileName);
string boundary = "---------------------------41184676334";
imageShackWebRequest.ContentType = @"multipart/form-data; boundary=" + boundary;
string contentType;
switch (fileToUploadInfo.Extension.ToLower())
{
case ".jpg":
contentType = "image/jpg";
break;
case ".jpeg":
contentType = "image/jpeg";
break;
case ".gif":
contentType = "image/gif";
break;
case ".png":
contentType = "image/png";
break;
case ".bmp":
contentType = "image/bmp";
break;
case ".tif":
contentType = "image/tiff";
break;
case ".tiff":
contentType = "image/tiff";
break;
default:
contentType = "image/unknown";
break;
}
StringBuilder sb = new StringBuilder();
sb.Append("");
sb.Append(boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append("fileupload");
sb.Append("\"; filename=\"");
sb.Append(fileToUploadInfo.Name);
sb.Append("\"");
sb.Append("\r\n");
sb.Append("Content-Type: ");
sb.Append(contentType);
sb.Append("\r\n");
sb.Append("\r\n");
string imagePostHeader = sb.ToString();
byte[] imagePostHeaderBytes = Encoding.UTF8.GetBytes(imagePostHeader);
byte[] trailingBoundaryBytes = Encoding.ASCII.GetBytes("-----------------------------41184676334\r\n Content-Disposition: form-data; name=\"submit\"\r\n \r\n Upload\r\n -----------------------------41184676334--\r\n");
FileStream imageFileStream = new FileStream(fileToUploadInfo.FullName, FileMode.Open, FileAccess.Read);
imageShackWebRequest.ContentLength = imagePostHeaderBytes.Length + imageFileStream.Length + trailingBoundaryBytes.Length;
Stream httpRequestStream = imageShackWebRequest.GetRequestStream();
httpRequestStream.Write(imagePostHeaderBytes, 0, imagePostHeaderBytes.Length);
byte[] imageFileBuffer = new Byte[checked((uint)Math.Min(4096, (int)imageFileStream.Length))];
int bytesRead = 0;
while ((bytesRead = imageFileStream.Read(imageFileBuffer, 0, imageFileBuffer.Length)) != 0)
{
httpRequestStream.Write(imageFileBuffer, 0, bytesRead);
}
httpRequestStream.Write(trailingBoundaryBytes, 0, trailingBoundaryBytes.Length);
HttpWebResponse imageShackWebResponse = imageShackWebRequest.GetResponse() as HttpWebResponse;
StreamReader Sr = new StreamReader(((HttpWebResponse)imageShackWebRequest.GetResponse()).GetResponseStream());
string Reponse = Sr.ReadToEnd();
Sr.Close(); // Et on ferme
Console.WriteLine(Reponse);
Console.ReadKey(); |
Partager