從UIWebView中呼叫iOS相簿,並選擇圖片上傳到Linux Web伺服器。
//
// ViewController.h
// Xcode_FileUpload
//
// Created by KirSsu Ryu on 12-8-7.
// Copyright (c) 2012年 __JModule__. All rights reserved.
//
#import <UIKit/UIKit.h>
//UIWebViewDelegate 代理類:跟javascript相互傳值。
//UINavigationControllerDelegate,UIImagePickerControllerDelegate 代理類:開啟相簿等一系列操作。
@interface ViewController : UIViewController<UIWebViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>{
UIWebView *myWebView;
UIImagePickerController *picker_library_;
}
//我的WebView控制元件
@property (nonatomic, retain) IBOutlet UIWebView *myWebView;
//相簿類的變數
@property (
@end
ViewController.m//
// ViewController.h
// Xcode_FileUpload
//
// Created by KirSsu Ryu on 12-8-7.
// Copyright (c) 2012年 __JModule__. All rights reserved.
//
#import "ViewController.h"
@interface ViewController()
@end
@implementation ViewController
@synthesize myWebView;
@synthesize picker_library_;
- (void)viewDidLoad
{
[super viewDidLoad];
//代理UIWebViewDelegate
myWebView.delegate = self;
//設定要載入的連結
NSURL *url = [NSURL URLWithString:@"http://*****/test/index.php"];
//建立一個請求物件
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//把請求傳送到webView裡,實現顯示內容
[myWebView loadRequest:request];
}
- (void)viewDidUnload
{
[self setMyWebView:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
//獲得從網站得到的值
#pragma mark --
#pragma mark UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
//獲得請求的URL,第一次是路徑,當在web上點選按鈕後獲得的是web穿過來的路徑。
NSString *requestString = [[request URL] absoluteString];
//根據":"拆分字串,返回陣列。
NSArray *components = [requestString componentsSeparatedByString:@":"];
//如果陣列內的元素大於1並且第一個元素的值相等
if ([components count] > 1 && [(NSString *)[components objectAtIndex:0]isEqualToString:@"gallery"]) {
if([(NSString *)[components objectAtIndex:1] isEqualToString:@"open"])
{
[self openGallery];
}
return NO;
}
return YES;
}
//開啟相簿
-(void)openGallery{
//初始化類
picker_library_ = [[UIImagePickerController alloc] init];
//指定幾總圖片來源
//UIImagePickerControllerSourceTypePhotoLibrary:表示顯示所有的照片。
//UIImagePickerControllerSourceTypeCamera:表示從攝像頭選取照片。
//UIImagePickerControllerSourceTypeSavedPhotosAlbum:表示僅僅從相簿中選取照片。
picker_library_.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//表示使用者可編輯圖片。
picker_library_.allowsEditing = YES;
//代理
picker_library_.delegate = self;
[self presentModalViewController: picker_library_
animated: YES];
}
//3.x 使用者選中圖片後的回撥
- (void)imagePickerController: (UIImagePickerController *)picker
didFinishPickingMediaWithInfo: (NSDictionary *)info
{
NSLog(@"3.x");
//獲得編輯過的圖片
UIImage* image = [info objectForKey: @"UIImagePickerControllerEditedImage"];
[self dismissModalViewControllerAnimated:YES];
[self imageUpload:image];
}
//2.x 使用者選中圖片之後的回撥
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage*)image editingInfo:(NSDictionary *)editingInfo
{
NSLog(@"2.x");
NSMutableDictionary * dict= [NSMutableDictionary dictionaryWithDictionary:editingInfo];
[dict setObject:image forKey:@"UIImagePickerControllerEditedImage"];
//直接呼叫3.x的處理函式
[self imagePickerController:picker didFinishPickingMediaWithInfo:dict];
}
// 使用者選擇取消
- (void) imagePickerControllerDidCancel: (UIImagePickerController *)picker
{
[self dismissModalViewControllerAnimated:YES];
}
//上傳圖片方法
- (void) imageUpload:(UIImage *) image{
//把圖片轉換成imageDate格式
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
//傳送路徑
NSString *urlString = @"http://*****/test/upload.php";
//建立請求物件
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] init];
//設定請求路徑
[request setURL:[NSURL URLWithString:urlString]];
//請求方式
[request setHTTPMethod:@"POST"];
//一連串上傳頭標籤
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary]dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name="userfile"; filename="vim_go.jpg"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[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]];
[request setHTTPBody:body];
//上傳檔案開始
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nilerror:nil];
//獲得返回值
NSString *returnString = [[NSString alloc] initWithData:returnDataencoding:NSUTF8StringEncoding];
NSLog(@"%@",returnString);
}
@end
======ios端結束,再看下web端======= index.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>測試</title> <script type="text/javascript"> function uploads(){ sendCommand("open"); } function sendCommand(cmd){ var url = "gallery:"+cmd; document.location = url; } </script> </head> <body> <a href="#"><img src="upload.jpg" alt="上傳按鈕" onclick="uploads();" /></a> </body> </html> upload.php <? $uploaddir = $_SERVER["DOCUMENT_ROOT"].'/test/upload/'; //這個目錄必須得有許可權才行。 $file = basename($_FILES['userfile']['name']); $uploadfile = $uploaddir . $file; if(move_uploaded_file($_FILES['userfile']['tmp_name'],$uploadfile)){ echo "OK"; }else{ echo "ERROR"; } ?> 所有的工作都完成了。 下面附圖。 圖片1是 上傳圖片的按鈕,隨便找了個圖片代替的上傳按鈕。圖片2是我的相簿
圖片3是選擇圖片
圖片4是剪下圖片,當按choose的時候,圖片就可以上傳到伺服器了。
圖片5是已經上傳好的圖片,看路徑。 好了,寫完了~~