六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 507|回复: 0

iOS开发之结合asp.net webservice实现文件上传下载

[复制链接]
 楼主| 发表于 2013-6-27 14:01:19 | 显示全部楼层 |阅读模式
OS开发中会经常用到文件上传下载的功能,这篇文件将介绍一下使用asp.net webservice实现文件上传下载。首先,让我们看下文件下载。
这里我们下载cnblogs上的一个zip文件。使用NSURLRequest+NSURLConnection可以很方便的实现这个功能。
同步下载文件:
  1. NSString *urlAsString = @"http://files.cnblogs.com/zhuqil/UIWebViewDemo.zip";
  2.         NSURL    *url = [NSURL URLWithString:urlAsString];
  3.         NSURLRequest *request = [NSURLRequest requestWithURL:url];
  4.         NSError *error = nil;
  5.         NSData   *data = [NSURLConnection sendSynchronousRequest:request
  6.                                                returningResponse:nil
  7.                                                            error:&error];
  8.         /* 下载的数据 */
  9.         if (data != nil){
  10.             NSLog(@"下载成功");
  11.             if ([data writeToFile:@"UIWebViewDemo.zip" atomically:YES]) {
  12.                 NSLog(@"保存成功.");
  13.             }
  14.             else
  15.             {
  16.                 NSLog(@"保存失败.");
  17.             }
  18.         } else {
  19.             NSLog(@"%@", error);
  20.         }
复制代码
异步下载文件:
  1. - (void)viewDidLoad
  2. {
  3.     [super viewDidLoad];
  4.     //文件地址
  5.     NSString *urlAsString = @"http://files.cnblogs.com/zhuqil/UIWebViewDemo.zip";
  6.     NSURL    *url = [NSURL URLWithString:urlAsString];
  7.     NSURLRequest *request = [NSURLRequest requestWithURL:url];
  8.     NSMutableData *data = [[NSMutableData alloc] init];
  9.     self.connectionData = data;
  10.     [data release];
  11.     NSURLConnection *newConnection = [[NSURLConnection alloc]
  12.                                       initWithRequest:request
  13.                                       delegate:self
  14.                                       startImmediately:YES];
  15.     self.connection = newConnection;
  16.     [newConnection release];
  17.     if (self.connection != nil){
  18.        NSLog(@"Successfully created the connection");
  19.     } else {
  20.         NSLog(@"Could not create the connection");
  21.     }
  22. }




  23. - (void) connection:(NSURLConnection *)connection
  24.             didFailWithError:(NSError *)error{
  25.     NSLog(@"An error happened");
  26.     NSLog(@"%@", error);
  27. }
  28. - (void) connection:(NSURLConnection *)connection
  29.               didReceiveData:(NSData *)data{
  30.     NSLog(@"Received data");
  31.     [self.connectionData appendData:data];
  32. }
  33. - (void) connectionDidFinishLoading
  34. :(NSURLConnection *)connection{
  35.     /* 下载的数据 */

  36.         NSLog(@"下载成功");
  37.         if ([self.connectionData writeToFile:@"UIWebViewDemo.zip" atomically:YES]) {
  38.             NSLog(@"保存成功.");
  39.         }
  40.         else
  41.         {
  42.             NSLog(@"保存失败.");
  43.         }
  44.   
  45.     /* do something with the data here */
  46. }
  47. - (void) connection:(NSURLConnection *)connection
  48.           didReceiveResponse:(NSURLResponse *)response{
  49.     [self.connectionData setLength:0];
  50. }

  51. - (void) viewDidUnload{
  52.     [super viewDidUnload];
  53.     [self.connection cancel];
  54.     self.connection = nil;
  55.     self.connectionData = nil;
  56. }
复制代码
从上面两段代码中可以看到同步与异步下载的区别,大部分时候我们使用异步下载文件。在asp.net webservice中可以将文件的地址返回到iOS系统,iOS系统在去请求下载该文件。
上传文件
我们先使用VB.Net写一个webservice方法,用于接收上传上来的文件数据,代码如下。
  1. <WebMethod(Description:="上传文件!")> _
  2. Public Function UploadFile() As XmlDocument
  3.         Dim doc As XmlDocument = New XmlDocument()
  4.         Try
  5.             Dim postCollection As HttpFileCollection = Context.Request.Files
  6.             Dim aFile As HttpPostedFile = postCollection("media")
  7.             aFile.SaveAs(Server.MapPath(".") + "/" + Path.GetFileName(aFile.FileName))
  8.             doc.LoadXml("<xml>ok</xml>")
  9.             Return doc
  10.         Catch ex As Exception
  11.             doc.LoadXml("<xml>fail</xml>")
  12.             Return doc
  13.         End Try
  14.     End Function
复制代码
文件上传接口
定义一个类PicOperation用于处理上传图片:
  1. @interface PicOperation : NSOperation
  2. {
  3.     UIImage *theImage;
  4. }
  5. @property (retain) UIImage *theImage;
  6. @end
复制代码
  1. //
  2. //  PicOperation.m
  3. //  DownLoading
  4. //
  5. //  Created by skylin zhu on 11-7-30.
  6. //  Copyright 2011年 mysoft. All rights reserved.
  7. //

  8. #import "PicOperation.h"

  9. #define NOTIFY_AND_LEAVE(X) {[self cleanup:X]; return;}
  10. #define DATA(X)        [X dataUsingEncoding:NSUTF8StringEncoding]

  11. // Posting constants
  12. #define IMAGE_CONTENT @"Content-Disposition: form-data; name="%@"; filename="image.jpg"\r\nContent-Type: image/jpeg\r\n\r\n"
  13. #define STRING_CONTENT @"Content-Disposition: form-data; name="%@"\r\n\r\n"
  14. #define MULTIPART @"multipart/form-data; boundary=------------0x0x0x0x0x0x0x0x"

  15. @implementation PicOperation
  16. @synthesize theImage;

  17. //创建postdata
  18. - (NSData*)generateFormDataFromPostDictionary:(NSDictionary*)dict
  19. {
  20.     id boundary = @"------------0x0x0x0x0x0x0x0x";
  21.     NSArray* keys = [dict allKeys];
  22.     NSMutableData* result = [NSMutableData data];
  23.        
  24.     for (int i = 0; i < [keys count]; i++)
  25.     {
  26.         id value = [dict valueForKey: [keys objectAtIndex:i]];
  27.         [result appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
  28.                
  29.                 if ([value isKindOfClass:[NSData class]])
  30.                 {
  31.                         // handle image data
  32.                         NSString *formstring = [NSString stringWithFormat:IMAGE_CONTENT, [keys objectAtIndex:i]];
  33.                         [result appendData: DATA(formstring)];
  34.                         [result appendData:value];
  35.                 }
  36.                 else
  37.                 {
  38.                         // all non-image fields assumed to be strings
  39.                         NSString *formstring = [NSString stringWithFormat:STRING_CONTENT, [keys objectAtIndex:i]];
  40.                         [result appendData: DATA(formstring)];
  41.                         [result appendData:DATA(value)];
  42.                 }
  43.                
  44.                 NSString *formstring = @"\r\n";
  45.         [result appendData:DATA(formstring)];
  46.     }
  47.        
  48.         NSString *formstring =[NSString stringWithFormat:@"--%@--\r\n", boundary];
  49.     [result appendData:DATA(formstring)];
  50.     return result;
  51. }
  52. //上传图片
  53. - (NSString *) UpLoading
  54. {
  55.         if (!self.theImage)
  56.                 NOTIFY_AND_LEAVE(@"Please set image before uploading.");
  57.    
  58.    
  59.         NSMutableDictionary* post_dict = [[NSMutableDictionary alloc] init];
  60.    
  61.         [post_dict setObject:@"Posted from iPhone" forKey:@"message"];
  62.         [post_dict setObject:UIImageJPEGRepresentation(self.theImage, 0.75f) forKey:@"media"];
  63.        
  64.         NSData *postData = [self generateFormDataFromPostDictionary:post_dict];
  65.         [post_dict release];
  66.        
  67.     NSString *baseurl = @"http://10.5.23.121:7878/WorkflowService.asmx/UploadFile";
  68.     NSURL *url = [NSURL URLWithString:baseurl];
  69.     NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
  70.     if (!urlRequest) NOTIFY_AND_LEAVE(@"Error creating the URL Request");
  71.        
  72.     [urlRequest setHTTPMethod: @"POST"];
  73.         [urlRequest setValue:MULTIPART forHTTPHeaderField: @"Content-Type"];
  74.     [urlRequest setHTTPBody:postData];
  75.        
  76.         // Submit & retrieve results
  77.     NSError *error;
  78.     NSURLResponse *response;
  79.         NSLog(@"Contacting TwitPic....");
  80.     NSData* result = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
  81.     if (!result)
  82.         {
  83.                 [self cleanup:[NSString stringWithFormat:@"Submission error: %@", [error localizedDescription]]];
  84.                 return;
  85.         }
  86.        
  87.         // Return results
  88.     NSString *outstring = [[[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding] autorelease];
  89.     return outstring;
  90. }
  91. @end
复制代码
这里我主要定义了两个方法,一个是generateFormDataFromPostDictionary用于创建post form data,一个是UpLoading供调用的类上传图片,这个类需要一个UIimage的对象。
类定义好了,上传图片就非常方便了,看下面代码:
  1. PicOperation *pic = [[PicOperation alloc] init];
  2.     pic.theImage=[UIImage imageNamed:@"meinv4.jpg"];;
  3.     NSString *result = [pic UpLoading];
  4.     NSLog(result);
复制代码
本文摘自: http://www.cnblogs.com/zhuqil/archive/2011/07/30/2122019.html






该会员没有填写今日想说内容.
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表