您的位置:首页 > 其它

wcf rest 服务用于安卓和ISO调用2-------文件上传

2016-02-02 10:55 633 查看
接着上次写.......................

这次利用wcf rest 上传文件.废话不多说.接着写代码.

在上次的接口中添加上传文件方法UpLoad,代码如下:

[WebInvoke(Method = "POST", UriTemplate = "UpLoad/{fileName}",
ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
[System.ComponentModel.Description("上传文件")]
bool UpLoad(System.IO.Stream stream, string fileName);


然后编写接口的方法实现:

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);
}
//清空缓冲区
fs.Flush();
//关闭流
fs.Close();
return true;
}
catch (Exception ex)
{
LogHelper.Error("保存文件失败", ex);
return false;
}
}


  这里保存的路径,我就固定到d:\test文件夹下面.然后在浏览器里面查看一下.

  接下来就编写客户端代码进行调用.接着上次的控制台应用程序写.代码如下图

public static  void UploadFile()
{
Console.WriteLine("--------------上传文件----------------");

HttpClient httpClient = new HttpClient();
string uri = "http://localhost:31572/Service1.svc/UpLoad/";
try
{
string str;
do
{
Stopwatch stopwatch = new Stopwatch();
Console.WriteLine("请输入上传文件路径:");
string filePath = Console.ReadLine();
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
string fileName = filePath.Substring(filePath.LastIndexOf("\\", StringComparison.Ordinal)+1);
Console.WriteLine("开始上传文件...");
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("文件:{0},上传结果:{1}", fileName, response.Result.Content.ReadAsStringAsync().Result);
Console.WriteLine("上传文件所需时间:{0}", stopwatch.ElapsedMilliseconds);
}
else
{
Console.WriteLine("请输入正确的文件路径");
}
Console.WriteLine("y/n是否继续上传?");
str = Console.ReadLine();
} while (str=="y");
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.Read();
}
}


  最后效果如下图:



下一篇就是soap和rest如何一起使用.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: