ios 上传单张图片到服务器

来源:互联网 发布:匿名内部类java构造器 编辑:程序博客网 时间:2024/04/19 15:15


一、将图片压缩,转为二进制流进行上传

    NSData* data;    NSString* imageFormat = @"";    if(nil != UIImagePNGRepresentation(editedImage))    {        //将图片转换为JPG格式的二进制数据        data = UIImageJPEGRepresentation(editedImage, 1);        imageFormat = @"jpeg";    }    else    {        //将图片转换为PNG格式的二进制数据        data = UIImagePNGRepresentation(editedImage);        imageFormat = @"png";    }        NSString* url = [NSString stringWithFormat:@"xxx/upload/%@",@"image"];    NSString* requestURL = [NSString stringWithFormat:@"%@",url];        ASIFormDataRequest* request = [ASIFormDataRequest requestWithURL:[[NSURL alloc]initWithString:requestURL]];    [request setRequestMethod:@"POST"];    [request addRequestHeader:@"Content-Type" value:@"image/jpeg"];        //上传二进制数据、或者文件    [request setData:data withFileName:[NSString stringWithFormat:@"file.%@",imageFormat] andContentType:@"application/json;charset=UTF-8" forKey:@"uploadFile"];        //上传基本类型数据    //        [request setPostValue:fileType forKey:@"fileType"];    //        [request setPostValue:uploadFile forKey:@"file"];        [request setDelegate:self];    [request setTimeOutSeconds:10];    //        [request setUploadProgressDelegate:self];    [request setDidFailSelector:@selector(uploadFailed:)];    [request setDidFinishSelector:@selector(uploadFinished:)];    [request startSynchronous];

二、成功失败后处理

-(void)uploadFailed:(ASIHTTPRequest*)request{    NSError* error = [request error];    NSLog(@"%@",error);}-(void)uploadFinished:(ASIHTTPRequest*)request{    NSLog(@"Finished uploading %llu bytes of data", [request postLength]);    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request responseData] options:NSJSONReadingMutableLeaves error:nil];        self.imagePath = [result objectForKey:@"rows"];    if(0 == self.imagePath.length)    {        [[AppDelegate sharedInstance] presentMessageTips:@"网络异常"];    }    NSLog(self.imagePath);}


0 0
原创粉丝点击