iOS中文件的上传下载功能
2016-03-21 09:48
183 查看
iOS开发中会经常用到文件上传下载的功能,这篇文件将介绍一下使用asp.net webservice实现文件上传下载。
首先,让我们看下文件下载。
这里我们下载cnblogs上的一个zip文件。使用NSURLRequest+NSURLConnection可以很方便的实现这个功能。
同步下载文件:
复制代码
复制代码
异步下载文件:
复制代码
(void)viewDidLoad
{
[super viewDidLoad];
//文件地址
NSString *urlAsString = @”http://files.cnblogs.com/zhuqil/UIWebViewDemo.zip“;
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{
/* 下载的数据 */
/* 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;
}
复制代码
从上面两段代码中可以看到同步与异步下载的区别,大部分时候我们使用异步下载文件。在asp.net webservice中可以将文件的地址返回到iOS系统,iOS系统在去请求下载该文件。
上传文件
我们先使用VB.Net写一个webservice方法,用于接收上传上来的文件数据,代码如下。
?
_
Public
Function
UploadFile() As
XmlDocument
doc As
XmlDocument = New
XmlDocument()
postCollection As
HttpFileCollection = Context.Request.Files
aFile As
HttpPostedFile = postCollection(“media”)
+ “/”
Path.GetFileName(aFile.FileName))
doc
ex As
Exception
doc
Try
Function
文件上传接口
定义一个类PicOperation用于处理上传图片:
?
@interface
PicOperation : NSOperation
{
*theImage;
}
@property
(retain) UIImage *theImage;
@end
[objc] view plain copy
这里我主要定义了两个方法,一个是generateFormDataFromPostDictionary用于创建post form data,一个是UpLoading供调用的类上传图片,这个类需要一个UIimage的对象。
类定义好了,上传图片就非常方便了,看下面代码:
[objc] vie
a092
w plain copy
首先,让我们看下文件下载。
这里我们下载cnblogs上的一个zip文件。使用NSURLRequest+NSURLConnection可以很方便的实现这个功能。
同步下载文件:
复制代码
NSString *urlAsString = @"http://files.cnblogs.com/zhuqil/UIWebViewDemo.zip"; 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); }
复制代码
异步下载文件:
复制代码
(void)viewDidLoad
{
[super viewDidLoad];
//文件地址
NSString *urlAsString = @”http://files.cnblogs.com/zhuqil/UIWebViewDemo.zip“;
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;
}
复制代码
从上面两段代码中可以看到同步与异步下载的区别,大部分时候我们使用异步下载文件。在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] view plain copy
// // PicOperation.m // DownLoading // // Created by skylin zhu on 11-7-30. // Copyright 2011年 mysoft. All rights reserved. // #import "PicOperation.h" #define NOTIFY_AND_LEAVE(X) {[self cleanup:X]; return;} #define DATA(X) [X dataUsingEncoding:NSUTF8StringEncoding] // Posting constants #define IMAGE_CONTENT @"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n" #define STRING_CONTENT @"Content-Disposition: form-data; name=\"%@\"\r\n\r\n" #define MULTIPART @"multipart/form-data; boundary=------------0x0x0x0x0x0x0x0x" @implementation PicOperation @synthesize theImage; //创建postdata - (NSData*)generateFormDataFromPostDictionary:(NSDictionary*)dict { id boundary = @"------------0x0x0x0x0x0x0x0x"; NSArray* keys = [dict allKeys]; NSMutableData* result = [NSMutableData data]; for (int i = 0; i < [keys count]; i++) { id value = [dict valueForKey: [keys objectAtIndex:i]]; [result appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; if ([value isKindOfClass:[NSData class]]) { // handle image data NSString *formstring = [NSString stringWithFormat:IMAGE_CONTENT, [keys objectAtIndex:i]]; [result appendData: DATA(formstring)]; [result appendData:value]; } else { // all non-image fields assumed to be strings NSString *formstring = [NSString stringWithFormat:STRING_CONTENT, [keys objectAtIndex:i]]; [result appendData: DATA(formstring)]; [result appendData:DATA(value)]; } NSString *formstring = @"\r\n"; [result appendData:DATA(formstring)]; } NSString *formstring =[NSString stringWithFormat:@"--%@--\r\n", boundary]; [result appendData:DATA(formstring)]; return result; } //上传图片 - (NSString *) UpLoading { if (!self.theImage) NOTIFY_AND_LEAVE(@"Please set image before uploading."); NSMutableDictionary* post_dict = [[NSMutableDictionary alloc] init]; [post_dict setObject:@"Posted from iPhone" forKey:@"message"]; [post_dict setObject:UIImageJPEGRepresentation(self.theImage, 0.75f) forKey:@"media"]; NSData *postData = [self generateFormDataFromPostDictionary:post_dict]; [post_dict release]; NSString *baseurl = @"http://10.5.23.121:7878/WorkflowService.asmx/UploadFile"; NSURL *url = [NSURL URLWithString:baseurl]; NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; if (!urlRequest) NOTIFY_AND_LEAVE(@"Error creating the URL Request"); [urlRequest setHTTPMethod: @"POST"]; [urlRequest setValue:MULTIPART forHTTPHeaderField: @"Content-Type"]; [urlRequest setHTTPBody:postData]; // Submit & retrieve results NSError *error; NSURLResponse *response; NSLog(@"Contacting TwitPic...."); NSData* result = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error]; if (!result) { [self cleanup:[NSString stringWithFormat:@"Submission error: %@", [error localizedDescription]]]; return; } // Return results NSString *outstring = [[[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding] autorelease]; return outstring; } @end
这里我主要定义了两个方法,一个是generateFormDataFromPostDictionary用于创建post form data,一个是UpLoading供调用的类上传图片,这个类需要一个UIimage的对象。
类定义好了,上传图片就非常方便了,看下面代码:
[objc] vie
a092
w plain copy
PicOperation *pic = [[PicOperation alloc] init]; pic.theImage=[UIImage imageNamed:@"meinv4.jpg"];; NSString *result = [pic UpLoading]; NSLog(result);
相关文章推荐
- XE开发IOS下中文,英文,数字不对齐的解决办法
- iOS开发Xcode7真机调试教程
- iOS开发之音频解析第三方框架介绍
- iOS 设置视图半透明而子控件不透明
- 实例讲解如何在iOS应用开发中使用设计模式中的代理模式
- iOS开发-常用第三方开源框架介绍(你了解的ios只是冰山一角)
- iOS-控件之间的继承
- 【转】iOS的socket开发基础
- iOS开发调试技巧总结
- 使用Xcode为iOS应用项目创建PCH文件的方法及应用示例
- 学习Coding-iOS开源项目日志(一)
- IOS学习 iPad控件:POP控件器,分割窗口、浮动窗口、模态视图的使用
- iOS7之后pch头文件配置方法
- iOS开发证书"此证书的签发者无效"解决方法
- iOS 消息推送原理及实现Demo
- iOS 在 Xcode 中重命名项目名称
- iOS Provisioning Profile(Certificate)与Code Signing
- iOS-虚拟键盘遮盖问题
- iOS 开发之LLDB调试命令初探
- iOS简易蓝牙对战五子棋游戏设计思路之一——核心蓝牙通讯类的设计