(iPhone/iPad)檔案上傳與下載

安迪潘發表於2011-12-01

檔案下載:

-(void)downLoadImages: (NSString *)url saveAsImagesName:(NSString *)name{
    ASIHTTPRequest *request;
    request = [[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:url]]autorelease];
    [request setDownloadDestinationPath:[[NSHomeDirectory()stringByAppendingPathComponent:@"Documents"]stringByAppendingPathComponent:name]];
    
    [request setNumberOfTimesToRetryOnTimeout:2 ];
    [request startSynchronous];
    
    NSError *error = [request error];
    if (!error) {
        UIImage *img = [UIImage imageWithContentsOfFile:[request downloadDestinationPath]];
        if (img) {
            [imgPerson setImage:img];
        }
    }else{
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil  message:@"連線失敗!請檢查網路連線或服務是否正常!" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
}

其中:第一個引數url是檔案下載地址,第二個引數name是檔案儲存到本地的檔名。



檔案上傳:

//圖片上傳
- (void)uploadImage {
	
    NSData *imageData = UIImagePNGRepresentation(imgPerson.image);
	// setting up the URL to post to
    
    NSString *urlString = @"http://www.xxxx.com/lsmobile/UploadServlet";
	
	// setting up the request object now
	NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
	[request setURL:[NSURL URLWithString:urlString]];
	[request setHTTPMethod:@"POST"];
	
	/*
	 add some header info now
	 we always need a boundary when we post a file
	 also we need to set the content type
	 
	 You might want to generate a random boundary.. this is just the same 
	 as my output from wireshark on a valid html post
     */
	NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
	NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
	[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
	
	/*
	 now lets create the body of the post
     */
    
	NSMutableData *body = [NSMutableData data];
	[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];	
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n",strHeadPath] dataUsingEncoding:NSUTF8StringEncoding]];
    [strHeadPath release];
    strHeadPath=nil;
    
	[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
	[body appendData:[NSData dataWithData:imageData]];
	[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
	// setting the body of the post to the reqeust
	[request setHTTPBody:body];
    
	
	NSError *errorMsg=nil;
	// now lets make the connection to the web
	NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&errorMsg];
    
    
    if (!errorMsg) {
        NSString *returnString = [[[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding] autorelease];
        NSLog(returnString);
        
        if ([returnString isEqualToString:@"Fail"]) {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil  message:@"sorry,圖片上傳失敗,請嘗試重新提交" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil];
            [alert show];
            [alert release];
            
        }else{
            strImgPath=[[NSString alloc] initWithFormat:@"%@",returnString];//在更改操作中release
            uploadFlg=true;
        }
        [returnString release];
        returnString=nil;
    }else{
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil  message:@"連線失敗!請檢查網路連線或服務是否正常!" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil];
        [alert show];
        [alert release];
        
    }
    
}
本段程式碼中上傳的是圖片,如果想上傳其他檔案,可更改最初的NSData資料來源。


還有很多方法

更多上傳下載方法可參考:

1.iOS開發之結合asp.net webservice實現檔案上傳下載http://www.cnblogs.com/zhuqil/archive/2011/07/30/2122019.html

2.http://www.flyblog.info/catprogramming/392.html

3.http://iphone.zcentric.com/2008/08/29/post-a-uiimage-to-the-web/

4.http://zcentric.com/2008/08/29/post-a-uiimage-to-the-web/

相關文章