iOS开发中会经常用到文件上传下载的功能,这篇文件将介绍一下使用asp.net webservice实现文件上传下载。

首先,让我们看下文件下载。

这里我们下载cnblogs上的一个zip文件。使用NSURLRequest+NSURLConnection可以很方便的实现这个功能。

同步下载文件:


ios 文件选择 ios 选择文件上传_ios 文件选择



NSString *urlAsString = @"";
        NSURL    *url = [NSURL URLWithString:urlAsString];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        NSError *error = nil;
        NSData   *data = [NSURLConnection sendSynchronousRequest:request
                                               returningResponse:nil
                                                           error:&error];
/* 下载的数据 */
if (data != nil){
            NSLog(@"下载成功");
if ([data writeToFile:@"UIWebViewDemo.zip" atomically:YES]) {
                NSLog(@"保存成功.");
            }
else
            {
                NSLog(@"保存失败.");
            }
        } else {
            NSLog(@"%@", error);
        }



ios 文件选择 ios 选择文件上传_ios 文件选择


异步下载文件:


ios 文件选择 ios 选择文件上传_ios 文件选择



- (void)viewDidLoad
{
    [super viewDidLoad];
//文件地址
    NSString *urlAsString = @"";
    NSURL    *url = [NSURL URLWithString:urlAsString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSMutableData *data = [[NSMutableData alloc] init];
    self.connectionData = data;
    [data release];
    NSURLConnection *newConnection = [[NSURLConnection alloc]
                                      initWithRequest:request
delegate:self
                                      startImmediately:YES];
    self.connection = newConnection;
    [newConnection release];
if (self.connection != nil){
       NSLog(@"Successfully created the connection");
    } else {
        NSLog(@"Could not create the connection");
    }
}




- (void) connection:(NSURLConnection *)connection
            didFailWithError:(NSError *)error{
    NSLog(@"An error happened");
    NSLog(@"%@", error);
}
- (void) connection:(NSURLConnection *)connection
              didReceiveData:(NSData *)data{
    NSLog(@"Received data");
    [self.connectionData appendData:data];
}
- (void) connectionDidFinishLoading
:(NSURLConnection *)connection{
/* 下载的数据 */

        NSLog(@"下载成功");
if ([self.connectionData writeToFile:@"UIWebViewDemo.zip" atomically:YES]) {
            NSLog(@"保存成功.");
        }
else
        {
            NSLog(@"保存失败.");
        }

/* do something with the data here */
}
- (void) connection:(NSURLConnection *)connection
          didReceiveResponse:(NSURLResponse *)response{
    [self.connectionData setLength:0];
}

- (void) viewDidUnload{
    [super viewDidUnload];
    [self.connection cancel];
    self.connection = nil;
    self.connectionData = nil;
}



ios 文件选择 ios 选择文件上传_ios 文件选择


从上面两段代码中可以看到同步与异步下载的区别,大部分时候我们使用异步下载文件。在asp.net webservice中可以将文件的地址返回到iOS系统,iOS系统在去请求下载该文件。

上传文件

我们先使用VB.Net写一个webservice方法,用于接收上传上来的文件数据,代码如下。



<WebMethod(Description:=          "上传文件!"          )> _         
          Public          Function           UploadFile()           As          XmlDocument         
                    Dim          doc           As          XmlDocument =           New          XmlDocument()         
                    Try         
                    Dim          postCollection           As          HttpFileCollection = Context.Request.Files         
                    Dim          aFile           As          HttpPostedFile = postCollection(          "media"          )         
                    aFile.SaveAs(Server.MapPath(          "."          ) +           "/"          + Path.GetFileName(aFile.FileName))         
                    doc.LoadXml(          "<xml>ok</xml>"          )         
                    Return          doc         
                    Catch          ex           As          Exception         
                    doc.LoadXml(          "<xml>fail</xml>"          )         
                    Return          doc         
                    End          Try         
                    End          Function


文件上传接口

定义一个类PicOperation用于处理上传图片:




@interface PicOperation : NSOperation          
          {         
                    UIImage *theImage;         
          }         
          @property (retain) UIImage *theImage;         
          @end


[objc] 
    
 
    
 
  
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.   
9. #import "PicOperation.h"  
10.   
11. #define NOTIFY_AND_LEAVE(X) {[self cleanup:X]; return;}  
12. #define DATA(X) [X dataUsingEncoding:NSUTF8StringEncoding]  
13.   
14. // Posting constants  
15. #define IMAGE_CONTENT @"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n"  
16. #define STRING_CONTENT @"Content-Disposition: form-data; name=\"%@\"\r\n\r\n"  
17. #define MULTIPART @"multipart/form-data; boundary=------------0x0x0x0x0x0x0x0x"  
18.   
19. @implementation PicOperation  
20. @synthesize theImage;  
21.   
22. //创建postdata  
23. - (NSData*)generateFormDataFromPostDictionary:(NSDictionary*)dict  
24. {  
25. id boundary = @"------------0x0x0x0x0x0x0x0x";  
26.  allKeys];  
27.  data];  
28.       
29. for (int i = 0; i < [keys count]; i++)   
30.     {  
31. id value = [dict valueForKey: [keys objectAtIndex:i]];  
32.  appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];  
33.           
34. if ([value isKindOfClass:[NSData class]])   
35.         {  
36. // handle image data  
37. NSString *formstring = [NSString stringWithFormat:IMAGE_CONTENT, [keys objectAtIndex:i]];  
38.  appendData: DATA(formstring)];  
39.  appendData:value];  
40.         }  
41. else   
42.         {  
43. // all non-image fields assumed to be strings  
44. NSString *formstring = [NSString stringWithFormat:STRING_CONTENT, [keys objectAtIndex:i]];  
45.  appendData: DATA(formstring)];  
46.  appendData:DATA(value)];  
47.         }  
48.           
49. NSString *formstring = @"\r\n";  
50.  appendData:DATA(formstring)];  
51.     }  
52.       
53. NSString *formstring =[NSString stringWithFormat:@"--%@--\r\n", boundary];  
54.  appendData:DATA(formstring)];  
55. return result;  
56. }  
57. //上传图片  
58. - (NSString *) UpLoading  
59. {  
60. if (!self.theImage)  
61. @"Please set image before uploading.");  
62.       
63.       
64.  alloc] init];  
65.       
66.  setObject:@"Posted from iPhone" forKey:@"message"];  
67.  setObject:UIImageJPEGRepresentation(self.theImage, 0.75f) forKey:@"media"];  
68.       
69. NSData *postData = [self generateFormDataFromPostDictionary:post_dict];  
70.  release];  
71.       
72. NSString *baseurl = @"http://10.5.23.121:7878/WorkflowService.asmx/UploadFile";   
73. NSURL *url = [NSURL URLWithString:baseurl];  
74. NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];  
75. if (!urlRequest) NOTIFY_AND_LEAVE(@"Error creating the URL Request");  
76.       
77.  setHTTPMethod: @"POST"];  
78.  setValue:MULTIPART forHTTPHeaderField: @"Content-Type"];  
79.  setHTTPBody:postData];  
80.       
81. // Submit & retrieve results  
82. NSError *error;  
83. NSURLResponse *response;  
84. @"Contacting TwitPic....");  
85.  sendSynchronousRequest:urlRequest returningResponse:&response error:&error];  
86. if (!result)  
87.     {  
88. self cleanup:[NSString stringWithFormat:@"Submission error: %@", [error localizedDescription]]];  
89. return;  
90.     }  
91.       
92. // Return results  
93. NSString *outstring = [[[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding] autorelease];  
94. return outstring;  
95. }  
96. @end


这里我主要定义了两个方法,一个是generateFormDataFromPostDictionary用于创建post form data,一个是UpLoading供调用的类上传图片,这个类需要一个UIimage的对象。

类定义好了,上传图片就非常方便了,看下面代码:

[objc] 
 
    
 
    
 
  
1. PicOperation *pic = [[PicOperation alloc] init];  
2. pic.theImage=[UIImage imageNamed:@"meinv4.jpg"];;  
3. NSString *result = [pic UpLoading];  
4. NSLog(result);


总结:这篇文章讲述了如何在iOS中结合asp.net webservice实现文件的上传和下载功能。


NSURLConnection 下载数据 -- IOS(实例


 


iPhone网络开发中如何使用NSURLConnection是本文要介绍的内容,这篇文章是翻译的苹果官方文档,想要看英文原版的可以到苹果网站查看,来看详细内容。

 

NSURLConnection 提供了很多灵活的方法下载URL内容也提供了一个简单的接口去创建和放弃连接,同时使用很多的delegate方法去支持连接过程的反馈和控制

 

如何创建一个连接呢?

 

为了下载url的内容,程序需要提供一个delegate对象,并且至少实现下面的方法



ios 文件选择 ios 选择文件上传_iOS_05

1. - (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSHTTPURLResponse*)response  
2. - (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data  
3. - (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error  
4. - (void)connectionDidFinishLoading:(NSURLConnection *)connection


 

NSURLConnect还提供了一个方便的类方法(class method) : sendSynchronousRequest:returningResponse:error: 可用来 同步地加载一个URL请求



ios 文件选择 ios 选择文件上传_iOS_05


1. + (NSData *)sendSynchronousRequest:    (NSURLRequest *)request      returningResponse:   (NSURLResponse **)response    error:  (NSError **)error

1. request 要装载的URL请求. 这个request 对象 作为初始化进程的一部分,被深度复制(deep-copied). 在这个方法返回之后, 再修改request, 将不会影响用在装载的过程中的request

2. reponse 输出参数, 由服务器返回的URL响应

3. error   输出参数, 如果在处理请求的过程中发生错误,就会使用.  无错误,就为NULL

 

举例一

 

1、先创建一个NSURL

2、在通过NSURL创建NSURLRequest,可以指定缓存规则和超时时间

3、创建NSURLConnection实例,指定NSURLRequest和一个delegate对象

 

如果创建失败,则会返回nil,如果创建成功则创建一个NSMutalbeData的实例用来存储数据

 

代码:


1. NSURLRequest *theRequest=[NSURLRequest requestWithURL:    
2. //www.sina.com.cn/”]  
3.                  cachePolicy:NSURLRequestUseProtocolCachePolicy    
4.                  timeoutInterval:60.0];    
5. NSURLConnection *theCnotallow=[[NSURLConnection alloc]         
6.                    initWithRequest:theRequest delegate:self];    
7. if(theConnection)    
8. {    
9. //创建NSMutableData  
10.   receivedData=[[NSMutableData data] retain];    
11. }else // 创建失败


 



ios 文件选择 ios 选择文件上传_iOS_05



  1. NSURLRequestUseProtocolCachePolicy //NSURLRequest默认的cache policy, 是最能保持一致性的协议。
  2. NSURLRequestReloadIgnoringCacheData  //忽略缓存直接从原始地址下载
  3. NSURLRequestReturnCacheDataElseLoad  //只有在cache中不存在data时才从原始地址下载
  4. NSURLRequestReturnCacheDataDontLoad  //允许app确定是否要返回cache数据,如果使用这种协议当本地不存在response的时候,创建NSURLConnection or NSURLDownload实例时将会马上返回nil;这类似于离线模式,没有建立网络连接;


 

NSURLConnection还有几个初始化函数,有个初始化函数可以做到创建连接但是并不马上开始下载,而是通过start:开始

 

当收到initWithRequest: delegate: 消息时,下载会立即开始,在代理(delegate)收到connectionDidFinishLoading:或者 connection:didFailWithError:消息之前可以通过给连接发送一个cancel:消息来中断下载。

 

当服务器提供了足够客户程序创建NSURLResponse对象的信息时,代理对象会收到一个connection:didReceiveResponse:消息,在消息内可以检查NSURLResponse对象和确定数据的预期长途,mime类型,文件名以及其他服务器提供的元信息

 

要注意,一个简单的连接也可能会收到多个connection:didReceiveResponse:消息当服务器连接重置或者一些罕见的原因(比如多组mime文档),代理都会收到该消息这时候应该重置进度指示,丢弃之前接收的数据



ios 文件选择 ios 选择文件上传_iOS_05


1. -(void)connection:(NSURLConnection *) connectiondidReceiveResponse:    
2.                         (NSURLResponse*)response    
3. {   
4.    [receiveData setLength:0];    
5. }

 

当下载开始的时候,每当有数据接收,代理会定期收到connection:didReceiveData:消息代理应当在实现中储存新接收的数据,下面的例子既是如此



1. -(void) connection:(NSURLConnection *) connection didReceiveData:    
2.             (NSData *) data    
3. {    
4.    [receiveData appendData:data];    
5.   
6. }

在上面的方法实现中,可以加入一个进度指示器,提示用户下载进度

 

当下载的过程中有错误发生的时候,代理会收到一个connection:didFailWithError消息,消息参数里面的NSError对象提供了具体的错误细节,它也能提供在用户信息字典里面失败的url请求(使用NSErrorFailingURLStringKey)

 

当代理接收到连接的connection:didFailWithError消息后,对于该连接不会在收到任何消息

 

举例



ios 文件选择 ios 选择文件上传_iOS_05

1. -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error    
2. {   
3. [connection release];    
4.   
5.   [receivedData release];    
6. "Connection failed! Error - %@ %@",    
7.           [error localizedDescription],    
8.           [[error userInfo] objectForKey:NSErrorFailingURLStringErrorKey]);    
9. }


 

最后,如果连接请求成功的下载,代理会接收connectionDidFinishLoading:消息代理不会收到其他的消息了,在消息的实现中,应该释放掉连接

 

举例:


1. -(void)connectionDidFinishLoading:(NSURLConnection *)connection    
2. {  
3. //do something with the data  
4. "succeeded  %d byte received",[receivedData length]);   
5.   
6. [connection release];    
7. [receivedData release];    
8. }


 

一个实现异步get请求的例子:


1. NSString *url = [NSString stringWithFormat:@"http://localhost/chat/messages.php?past=%ld&t=%ld",  
2.                      lastId, time(0) ];  
3.       
4.     NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];  
5.     [request setURL:[NSURL URLWithString:url]];  
6. "GET"];  
7.   
8.     NSURLConnection *cnotallow=[[NSURLConnection alloc] initWithRequest:request delegate:self];    
9. if
10.     {    
11.         receivedData = [[NSMutableData data] retain];    
12.     }     
13. else
14.     {    
15.     }   
16.   
17. - (void)timerCallback {  
18. //[timer release];
19.     [self getNewMessages];  
20. }  
21.   
22. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response    
23. {    
24.     [receivedData setLength:0];    
25. }    
26.   
27. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data    
28. {    
29.     [receivedData appendData:data];    
30. }    
31.   
32. - (void)connectionDidFinishLoading:(NSURLConnection *)connection    
33. {    
34. if
35.         [chatParser release];  
36.       
37. if
38.         messages = [[NSMutableArray alloc] init];  
39.   
40.     chatParser = [[NSXMLParser alloc] initWithData:receivedData];  
41. //set the delegate
42. //start parse
43.   
44.     [receivedData release];    
45.       
46.     [messageList reloadData];  
47.       
48.     NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:  
49.                                     [self methodSignatureForSelector: @selector(timerCallback)]];  
50.     [invocation setTarget:self];  
51.     [invocation setSelector:@selector(timerCallback)];  
52. //timer = [NSTimer scheduledTimerWithTimeInterval:5.0 invocation:invocation repeats:NO];
53. //if set yes,then very 5 seconds updata the table
54. }

  


 

一个实现同步Get请求的例子:


1. // 初始化请求
2. NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];           
3. // 设置URL
4. [request setURL:[NSURL URLWithString:urlStr]];  
5. // 设置HTTP方法
6. [request setHTTPMethod:@"GET"];  
7. // 发 送同步请求, 这里得returnData就是返回得数据了
8. NSData *returnData = [NSURLConnection sendSynchronousRequest:request   
9.                                                returningResponse:nil error:nil];   
10. // 释放对象
11. [request release];

 

 

来源:

http://mobile.51cto.com/iphone-281460.htm