クライアント - アップロード
static void UploadFile(string url, string file, string paramName, string contentType) { var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); var boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); var wr = (HttpWebRequest)WebRequest.Create(url); wr.ContentType = "multipart/form-data; boundary=" + boundary; wr.Method = "POST"; wr.KeepAlive = true; wr.Credentials = System.Net.CredentialCache.DefaultCredentials; var rs = wr.GetRequestStream(); var headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n"; var header = string.Format(headerTemplate, paramName, file, contentType); var headerbytes = System.Text.Encoding.UTF8.GetBytes(header); rs.Write(headerbytes, 0, headerbytes.Length); var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read); var buffer = new byte[4096]; var bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { rs.Write(buffer, 0, bytesRead); } fileStream.Close(); var trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); rs.Write(trailer, 0, trailer.Length); rs.Close(); WebResponse wresp = null; try { wresp = wr.GetResponse(); var stream2 = wresp.GetResponseStream(); var reader2 = new StreamReader(stream2); var result = reader2.ReadToEnd(); Console.WriteLine(string.Format("File uploaded. Server response is: {0}", result)); } catch (Exception ex) { if (wresp != null) { wresp.Close(); wresp = null; } Console.WriteLine("Exception occurred!! " + ex.ToString()); } finally { wr = null; } }データをポストするときのフォーマットを正確に作ってやって、そこに送りたいデータをはめ込むだけ。
クライアント - 使い方
UploadFile("http://localhost:55778/Image/PostImage", @"C:\test.JPG", "file", "image/jpeg");
ASP.NET MVC側 - ImageController
[HttpPost] public int PostImage() { var request = base.HttpContext.Request; if (request.Files.Count == 0) return 0; var httpPostedFile = request.Files[0] as HttpPostedFileBase; httpPostedFile.SaveAs("tekitouna_path.jpg"); return 1; }
上記のコードをASP.NET MVCサイトを動作させた状態でクライアントを実行すればサーバ側でファイルを受け取り保存することが可能なはずだ。
0 件のコメント:
コメントを投稿