WCF越来越流行,俺也在用,这是废话。项目中遇到需要图片上传,但是wcf上传会遇到一些异常,调试了N久,找了好多个解决方案才最终解决。代码直接贴上了
///
/// 笔记图片上传
///
///
///
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json, Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public Stream NoteUpFile(Stream image)
{
dynamic dy = null;
FileStream pFileStream = null;
try
{
byte[] bytes = ReadFully(image);//Stream转byte[]
string fileName = string.Format(@"Upload/Note/{0}.jpg", Utilitys.GetGuid);
string dirPath=System.AppDomain.CurrentDomain.BaseDirectory;
if (!Directory.Exists(dirPath + @"Upload/Note/"))//如果不存在就创建file文件夹
{
Directory.CreateDirectory(dirPath + @"Upload/Note/");//创建该文件夹
}
string path = dirPath + fileName;
pFileStream = new FileStream(path, FileMode.OpenOrCreate);
pFileStream.Write(bytes, 0, bytes.Length);
dy = new { code = "1", msg = "上传成功!", path = fileName };
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (pFileStream != null)
pFileStream.Close();
}
return Comm.GetStream(dy);//这个方法是将对象json序列化之后转换为Stream utf8模式,至于为什么要这样做只能说wcf太操蛋了 返回的json会多带一个 d:"" 酱紫的:{"d":"Hello World!"},完全正常!(这里的d:是微软自动为我们的数据加的一层壳)
}
我们将json转为流模式 就不会出现多一个D的问题了
///
///返回输出的字符///
/// json的数据集合
///
public staticStream GetStream(dynamic dy)
{string jsonString =GkXsn.Com.Utility.JsonHelper.Serializer(dy);return newMemoryStream(Encoding.UTF8.GetBytes(jsonString));
}
WCF并不支持Stream对象Length属性的序列化,也就是说,在客户端我们不能使用服务操作返回的Stream对象的Length属性。诸如stream.Length的调用会抛出NotSupportedException异常。采用此函数可解决上述问题
//Stream转byte[]///
///
///
private byte[] ReadFully(Stream stream)
{//初始化一个32k的缓存
byte[] buffer = new byte[32768];using (MemoryStream ms = newMemoryStream())
{//返回结果后会自动回收调用该对象的Dispose方法释放内存//不停的读取
while (true)
{int read = stream.Read(buffer, 0, buffer.Length);//直到读取完最后的3M数据就可以返回结果了
if (read <= 0)returnms.ToArray();
ms.Write(buffer,0, read);
}
}
}