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

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

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

这里我们下载cnblogs上的一个zip文件。使用NSURLRequest+NSURLConnection可以很方便的实现这个功能。在asp.net webservice中可以将文件的地址返回到iOS系统,iOS系统再通过这个url去请求下载该文件。这里为了简单起见,直接将url写道代码里面了。我们可以使用两种方式去下载文件。

1、同步下载文件:

[plain]  view plain copy
  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. }   


 

2、异步下载文件:DownLoadingViewController.h

[plain]  view plain copy
  1. //  
  2. //  DownLoadingViewController.h  
  3. //  DownLoading  
  4. //  
  5. //  Created by skylin zhu on 11-7-30.  
  6. //  Copyright 2011年 mysoft. All rights reserved.  
  7. //  
  8.   
  9. #import <UIKit/UIKit.h>  
  10.   
  11. @interface DownLoadingViewController : UIViewController {  
  12.     NSURLConnection *connection;    
  13.     NSMutableData *connectionData;  
  14. }  
  15. @property (nonatomic,retain) NSURLConnection *connection;     
  16. @property (nonatomic,retain) NSMutableData *connectionData;  
  17. @end  


 DownLoadingViewController.m

[plain]  view plain copy
  1. //  
  2. //  DownLoadingViewController.m  
  3. //  DownLoading  
  4. //  
  5. //  Created by skylin zhu on 11-7-30.  
  6. //  Copyright 2011年 mysoft. All rights reserved.  
  7. //  
  8.   
  9. #import "DownLoadingViewController.h"  
  10.   
  11. @implementation DownLoadingViewController  
  12. @synthesize connection,connectionData;  
  13. - (void)dealloc  
  14. {  
  15.     [super dealloc];  
  16. }  
  17.   
  18. - (void)didReceiveMemoryWarning  
  19. {  
  20.     // Releases the view if it doesn't have a superview.  
  21.     [super didReceiveMemoryWarning];  
  22.       
  23.     // Release any cached data, images, etc that aren't in use.  
  24. }  
  25.   
  26. #pragma mark - View lifecycle  
  27.   
  28.   
  29. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.  
  30. - (void)viewDidLoad  
  31. {  
  32.     [super viewDidLoad];  
  33.     //文件地址  
  34.     NSString *urlAsString = @"http://files.cnblogs.com/zhuqil/UIWebViewDemo.zip";  
  35.     NSURL    *url = [NSURL URLWithString:urlAsString];  
  36.     NSURLRequest *request = [NSURLRequest requestWithURL:url];  
  37.     NSMutableData *data = [[NSMutableData alloc] init];  
  38.     self.connectionData = data;  
  39.     [data release];  
  40.     NSURLConnection *newConnection = [[NSURLConnection alloc]  
  41.                                       initWithRequest:request  
  42.                                       delegate:self  
  43.                                       startImmediately:YES];  
  44.     self.connection = newConnection;  
  45.     [newConnection release];  
  46.     if (self.connection != nil){  
  47.        NSLog(@"Successfully created the connection");  
  48.     } else {  
  49.         NSLog(@"Could not create the connection");  
  50.     }  
  51. }  
  52.   
  53.   
  54.   
  55.   
  56. - (void) connection:(NSURLConnection *)connection  
  57.             didFailWithError:(NSError *)error{  
  58.     NSLog(@"An error happened");  
  59.     NSLog(@"%@", error);  
  60. }  
  61. - (void) connection:(NSURLConnection *)connection  
  62.               didReceiveData:(NSData *)data{  
  63.     NSLog(@"Received data");  
  64.     [self.connectionData appendData:data];  
  65. }  
  66. - (void) connectionDidFinishLoading  
  67. :(NSURLConnection *)connection{  
  68.     /* 下载的数据 */  
  69.   
  70.         NSLog(@"下载成功");  
  71.         if ([self.connectionData writeToFile:@"UIWebViewDemo.zip" atomically:YES]) {  
  72.             NSLog(@"保存成功.");  
  73.         }  
  74.         else  
  75.         {  
  76.             NSLog(@"保存失败.");  
  77.         }  
  78.     
  79.     /* do something with the data here */  
  80. }  
  81. - (void) connection:(NSURLConnection *)connection  
  82.           didReceiveResponse:(NSURLResponse *)response{  
  83.     [self.connectionData setLength:0];  
  84. }  
  85.   
  86. - (void) viewDidUnload{  
  87.     [super viewDidUnload];  
  88.     [self.connection cancel];  
  89.     self.connection = nil;  
  90.     self.connectionData = nil;  
  91. }  
  92.   
  93. @end  

从上面两段代码中可以看到同步与异步下载的区别,大部分时候我们使用异步下载文件。

上传文件

我们先使用VB.Net写一个webservice方法,用于接收上传上来的文件数据,我们可以从Request.Files中获取上传上来的文件数据。代码如下。

[vb]  view plain copy
  1. <WebMethod(Description:="上传文件!")> _  
  2. ic 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用于处理上传图片:PicOperation.h

[plain]  view plain copy
  1. //  
  2. //  PicOperation.h  
  3. //  DownLoading  
  4. //  
  5. //  Created by skylin zhu on 11-7-30.  
  6. //  Copyright 2011年 mysoft. All rights reserved.  
  7. //  
  8.   
  9. #import <Foundation/Foundation.h>  
  10.   
  11. @interface PicOperation : NSOperation   
  12. {  
  13.     UIImage *theImage;  
  14. }  
  15. @property (retain) UIImage *theImage;  
  16. @end  

 

PicOperation.m:

[plain]  view plain copy
  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.     NSArray* keys = [dict allKeys];  
  27.     NSMutableData* result = [NSMutableData data];  
  28.       
  29.     for (int i = 0; i < [keys count]; i++)   
  30.     {  
  31.         id value = [dict valueForKey: [keys objectAtIndex:i]];  
  32.         [result 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.             [result appendData: DATA(formstring)];  
  39.             [result 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.             [result appendData: DATA(formstring)];  
  46.             [result appendData:DATA(value)];  
  47.         }  
  48.           
  49.         NSString *formstring = @"\r\n";  
  50.         [result appendData:DATA(formstring)];  
  51.     }  
  52.       
  53.     NSString *formstring =[NSString stringWithFormat:@"--%@--\r\n", boundary];  
  54.     [result appendData:DATA(formstring)];  
  55.     return result;  
  56. }  
  57. //上传图片  
  58. - (NSString *) UpLoading  
  59. {  
  60.     if (!self.theImage)  
  61.         NOTIFY_AND_LEAVE(@"Please set image before uploading.");  
  62.       
  63.       
  64.     NSMutableDictionary* post_dict = [[NSMutableDictionary alloc] init];  
  65.       
  66.     [post_dict setObject:@"Posted from iPhone" forKey:@"message"];  
  67.     [post_dict setObject:UIImageJPEGRepresentation(self.theImage, 0.75f) forKey:@"media"];  
  68.       
  69.     NSData *postData = [self generateFormDataFromPostDictionary:post_dict];  
  70.     [post_dict 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.     [urlRequest setHTTPMethod: @"POST"];  
  78.     [urlRequest setValue:MULTIPART forHTTPHeaderField: @"Content-Type"];  
  79.     [urlRequest setHTTPBody:postData];  
  80.       
  81.     // Submit & retrieve results  
  82.     NSError *error;  
  83.     NSURLResponse *response;  
  84.     NSLog(@"Contacting TwitPic....");  
  85.     NSData* result = [NSURLConnection 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的对象。

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

[plain]  view plain copy
  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实现文件的上传和下载功能。


文章转载自:http://blog.csdn.net/zhuqilin0/article/details/6646743

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值