上傳檔案至伺服器,上傳檔案伺服器

來源:互聯網
上載者:User

上傳檔案至伺服器,上傳檔案伺服器

//上傳圖片-(void)showActionSheet{    //在這裡呼出下方功能表按鈕項    myActionSheet = [[UIActionSheet alloc]                     initWithTitle:nil                     delegate:self                     cancelButtonTitle:@"取消"                     destructiveButtonTitle:nil                     otherButtonTitles: @"開啟照相機", @"從手機相簿擷取",nil];        [myActionSheet showInView:self.view];    [myActionSheet release];    }- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{            //呼出的功能表按鈕點擊後的響應    if (buttonIndex == myActionSheet.cancelButtonIndex)    {        NSLog(@"取消");    }        switch (buttonIndex)    {        case 0:  //開啟照相機拍照            [self takePhoto];            break;                    case 1:  //開啟本地相簿            [self LocalPhoto];            break;    }}//開始拍照-(void)takePhoto{    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])    {        UIImagePickerController *picker = [[UIImagePickerController alloc] init];        picker.delegate = self;        //設定拍照後的圖片可被編輯        picker.allowsEditing = YES;        picker.sourceType = sourceType;        [picker release];        [self presentViewController:picker animated:YES completion:nil];    }else    {        NSLog(@"類比其中無法開啟照相機,請在真機中使用");    }}//開啟本地相簿-(void)LocalPhoto{    UIImagePickerController *picker = [[UIImagePickerController alloc] init];        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;    picker.delegate = self;    //設定選擇後的圖片可被編輯    picker.allowsEditing = YES;    [self presentViewController:picker animated:YES completion:nil];    [picker release];}//當選擇一張圖片後進入這裡-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{        NSString *type = [info objectForKey:UIImagePickerControllerMediaType];        //當選擇的類型是圖片    if ([type isEqualToString:@"public.image"])    {   NSLog(@"您選擇了該圖片");        //先把圖片轉成NSData        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];        NSData *data;        if (UIImagePNGRepresentation(image) == nil)        {            data = UIImageJPEGRepresentation(image, 1.0);        }        else        {            data = UIImagePNGRepresentation(image);        }                        //圖片儲存的路徑        //這裡將圖片放在沙箱的documents檔案夾中        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];                        //檔案管理工具        NSFileManager *fileManager = [NSFileManager defaultManager];                //把剛剛圖片轉換的data對象拷貝至沙箱中 並儲存為image.png        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];                //得到選擇後沙箱中圖片的完整路徑        filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/image.png"];                //關閉相簿介面        [picker dismissViewControllerAnimated:YES completion:nil];                [self imageUpload:image];                    }    }- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{    NSLog(@"您取消了選擇圖片");    [picker dismissViewControllerAnimated:YES completion:nil];}//上傳圖片到伺服器方法,採用了ASIFormDataRequest方法- (void) imageUpload:(UIImage *) image{        UIImage *im = [UIImage imageWithContentsOfFile:filePath];//通過path圖片路徑擷取圖片    NSData *data = UIImagePNGRepresentation(im);//擷取圖片資料    /*     ios中擷取圖片的方法有兩種,一種是UIImageJPEGRepresentation ,一種是UIImagePNGRepresentation     前者擷取到圖片的資料量要比後者的小很多。。     */    //伺服器位址    NSURL *url = [NSURL URLWithString:@"這裡寫入你的伺服器上傳地址"];    aRequest = [[ASIFormDataRequest alloc] initWithURL:url];        [aRequest setDelegate:self];//代理    [aRequest setRequestMethod:@"POST"];    //這個參數還不是很清楚    [aRequest addData:data withFileName:@"test.png" andContentType:@"image/png" forKey:@"file"];    [aRequest addRequestHeader:@"Content-Type" value:@"multipart/form-data"];//這裡的value值 需與伺服器端 一致        [aRequest startAsynchronous];//開始。非同步    [aRequest setDidFinishSelector:@selector(headPortraitSuccess)];//當成功後會自動觸發 headPortraitSuccess 方法    [aRequest setDidFailSelector:@selector(headPortraitFail)];//如果失敗會 自動觸發 headPortraitFail 方法    }-(void)headPortraitSuccess{    NSData * myResponseData = [aRequest responseData];  //擷取資料 :  調試的時候,在這裡, myResponseData的值一直是nil,不知道為什麼?    //將接收的資料轉換成NSString類型並列印出來    NSString *result = [[NSString alloc] initWithData:myResponseData encoding:NSUTF8StringEncoding];    NSLog(@"result------------>%@", result);    NSDictionary *data = [result objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];    NSArray *imgArray = [data objectForKey:@"data"];    NSString *imgpath=@"http://twww.51qed.com";    if ([imgArray count]) {        NSDictionary *imgInfo = [imgArray objectAtIndex:0];        imgpath = [imgpath stringByAppendingString:[imgInfo objectForKey:@"img"]];        NSLog(@"imgpath------------>%@", imgpath);    }    //設定H5圖片更新,ios調用JS代碼    [webview stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"setNewImg('%@');",imgpath]];    NSLog(@"上傳成功!");    [aRequest release];    }-(void)headPortraitFail{            NSLog(@"上傳失敗!");    }//開始request請求- (void)requestStarted:(ASIHTTPRequest *)request{            NSLog(@"開始請求!");    }@end
需匯入
<pre name="code" class="objc">#import "ASIHTTPRequest.h"#import "ASIFormDataRequest.h"#import "JSONKit.h"

這三個標頭檔

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.