iOS 實現檔案上傳下載
阿新 • • 發佈:2019-02-18
iOS開發中會經常用到檔案上傳下載的功能,這篇檔案將介紹一下使用asp.net webservice實現檔案上傳下載。
首先,讓我們看下檔案下載。
這裡我們下載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
|
//
// 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的物件。
類定義好了,上傳圖片就非常方便了,看下面程式碼:
PicOperation *pic = [[PicOperation alloc] init];
pic.theImage=[UIImage imageNamed:@"meinv4.jpg"];;
NSString *result = [pic UpLoading];
NSLog(result);
總結:這篇文章講述瞭如何在iOS中結合asp.net webservice實現檔案的上傳和下載功能。