The wcf rest service is used for Android and ISO call 2 ------- file upload, wcf2 -------
Next, the last write .......................
This time, I used wcf rest to upload files. I didn't talk much about it. I wrote the code.
Add the UpLoad method UpLoad to the last interface. 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 interface method implementation:
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);} // clear the buffer fs. flush (); // close the stream fs. close (); return true;} catch (Exception ex) {LogHelper. error ("failed to save the file", ex); return false ;}}
The path saved here is fixed under the d: \ test folder. check it in the browser.
Next, write the client code for calling. Then write the code for the last console application, as shown in figure
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 ("Enter the Upload File Path:"); string filePath = Console. readLine (); if (! String. isNullOrEmpty (filePath) & File. exists (filePath) {string fileName = filePath. 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. ensureSuccessStatusCo De (); Console. writeLine ("file: {0}, upload result: {1}", fileName, response. result. content. readAsStringAsync (). result); Console. writeLine ("File Upload time: {0}", stopwatch. elapsedMilliseconds);} else {Console. writeLine ("enter the correct file path");} Console. writeLine ("y/n continue to upload? "); Str = Console. readLine ();} while (str = "y");} catch (Exception ex) {Console. writeLine (ex); Console. read ();}}
The final effect is as follows:
The next article describes how to use soap and rest together.