And then the last time I wrote ........ .....
Use WCF rest to upload files this time. Don't say much. Then write the code.
In the last interface, add the upload file method upload, the code is as follows:
[WebInvoke (Method = "POST", UriTemplate = "Upload/{filename}", Responseformat = Webmessageformat.json, bodystyle = Webmessagebodystyle.bare)] [System.ComponentModel.Description ("Upload file")] bool UpLoad (System.IO.Stream Stream, string fileName);
Then write the method implementation of the interface:
public bool UpLoad (stream stream, string fileName) { try { byte[] buffer = new byte[1024]; FileStream fs = new FileStream (@ "d:\test\" + fileName, FileMode.Create, FileAccess.Write); int count = 0; while (count = stream. Read (buffer, 0, buffer. Length)) > 0) { fs. Write (buffer, 0, count); } Empties the buffer FS. Flush (); Close Stream fs. Close (); return true; } catch (Exception ex) { loghelper.error ("Save file Failed", ex); return false; } }
Here to save the path, I will pin it to the D:\test folder below. Then look inside the browser.
The next step is to write the client code for the call. Then the last console application wrote. Code such as
public static void UploadFile () {Console.WriteLine ("--------------Upload file----------------"); HttpClient HttpClient = new HttpClient (); String uri = "http://localhost:31572/Service1.svc/UpLoad/"; try {string str; do {Stopwatch Stopwatch = new Stopwatch (); Console.WriteLine ("Please enter path to upload file:"); String filePath = Console.ReadLine (); if (!string. IsNullOrEmpty (FilePath) && file.exists (FilePath)) {string fileName = fi Lepath.substring (filepath.lastindexof ("\ \", stringcomparison.ordinal) +1); Console.WriteLine ("Start uploading files ..."); Stream fs = new FileStream (FilePath, FileMode.Open); Httpcontent content = new Streamcontent (FS); Stopwatch. Start (); var response = hTtpclient.postasync (URI + fileName, content); Response. Result.ensuresuccessstatuscode (); Console.WriteLine ("File: {0}, upload result: {1}", FileName, Response. Result.Content.ReadAsStringAsync (). Result); Console.WriteLine ("Time required to upload the file: {0}", stopwatch. Elapsedmilliseconds); } else {Console.WriteLine ("Please enter the correct file path"); } Console.WriteLine ("Y/n continue uploading?"); str = Console.ReadLine (); } while (str== "Y"); } catch (Exception ex) {Console.WriteLine (ex); Console.read (); } }
The final effect is as follows:
The next article is how soap and rest work together.
WCF rest service for Android and ISO call 2-------file upload