码迷,mamicode.com
首页 > Web开发 > 详细

上传文件至服务器

时间:2014-12-03 19:26:08      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:ios上传文件

//上传图片
-(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"

这三个头文件

上传文件至服务器

标签:ios上传文件

原文地址:http://blog.csdn.net/u010427035/article/details/41699551

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!