转自:http://blog.csdn.net/musou_ldns/article/details/6933006
为某项目做的前期调查。目前可以实现检索,登录等相关机能,部分实现上传文件机能。上传文件仍有大小限制的问题,文件较大时,会出现上传失败的现象(2MB左右的文件会上传失败,),原因暂时不清楚。
项目内调查结果如下:WCF服务端:1.定义WCF协议接口(Interface)
- <pre name="code" class="csharp">[ServiceContract]
- public interface IUpLoadService
- {
- [OperationContract]
- [WebInvoke(Method = "POST", UriTemplate = "UploadFile/{fileName}")]
- void UploadFile(string fileName, Stream fileContent);
- [OperationContract]
- [WebGet(UriTemplate = "GetImageInfo/{name}", ResponseFormat = WebMessageFormat.Json)]
- ImageInfo GetImageInfo(string name);
- }</pre>
2.实现协议接口
- public class UpLoadService : IUpLoadService
- {
- public void UploadFile(string fileName, Stream fileContent)
- {
- FileStream fs = new FileStream("D:\\" + fileName, FileMode.OpenOrCreate);
- try
- {
- BinaryReader reader = new BinaryReader(fileContent);
- byte[] buffer;
- BinaryWriter writer = new BinaryWriter(fs);
- long offset = fs.Length;
- writer.Seek((int)offset, SeekOrigin.Begin);
- do
- {
- buffer = reader.ReadBytes(1024);
- writer.Write(buffer);
- } while (buffer.Length > 0);
- }
- catch (Exception e)
- {
- }
- finally
- {
- fs.Close();
- fileContent.Close();
- }
- }
- public ImageInfo GetImageInfo(string name) {
- return new ImageInfo {imageName=name, imageSize="122KB"};
- }
- }
3.Service配置文件:App.config
配置文件中,需要在自己service的endpoint节点中指定绑定方式binding="basicHttpBinding" , 以及绑定设置bindingConfiguration="MyServiceBinding",并在bindings节点中定义相应的basicHttpBinding的绑定设置。 这主要是为了设置上传文件的大小限制。 例如:
- <pre name="code" class="html"><binding name="DocumentExplorerServiceBinding" sendTimeout="00:10:00" transferMode="Streamed" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferPoolSize="2147483647" >
- <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
- <security mode="None" />
- </binding></pre>
iOS端程序:
1.上传文件
- NSURL *url = [NSURL URLWithString:@"http://172.16.xxx.xxx:82/Service.svc/UploadFile/myphoto.png"];
- request_ = [ASIFormDataRequest requestWithURL:url];
- [request_ setPostValue:@"myphoto1.png" forKey:@"fileName"];
- UIImage *image = [UIImage imageNamed:@"myphoto1.png"];
- NSData* imageData = [[NSData alloc] initWithData:UIImagePNGRepresentation(image)];
- [request_ appendPostData:imageData];
- [request_ setRequestMethod:@"POST"];
- [request_ setDidFinishSelector:@selector(requestFinished:)];
- [request_ setDidFailSelector:@selector(requestFailed:)];
- [request_ setDelegate:self];
- [request_ startAsynchronous];
2.调用方法取得返回值
- NSURL *url = [NSURL URLWithString:@"http://172.16.xxx.xxx:82/Service.svc/GetImageInfo/1.jpg"];
- ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
- [request startSynchronous];
- NSError *error = [request error];
- if (!error) {
- NSString *response = [request responseString];
- NSLog(response);
- }