iOS用ASIFormDataRequest实现图片上传

jopen 6年前

方法一:表单提交

    NSString *fileName = [[NSBundle mainBundle] pathForResource:@"color_blue" ofType:@"png"];      ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL: [NSURL URLWithString: url]];      //[request setPostValue:@"photo" forKey:@"type"];      [request setFile:fileName forKey:@"image"];  //    [request buildRequestHeaders];  //    [request buildPostBody];      [request setDelegate:delegate];      [request setTimeOutSeconds:TIME_OUT_SECONDS];      [request startAsynchronous];

方法二:POST:

/*   ios中获取图片的方法有两种,一种是UIImageJPEGRepresentation ,一种是UIImagePNGRepresentation   前者获取到图片的数据量要比后者的小很多。。  */      UIImage *im = [UIImage imageNamed:@"color_blue"];//通过path图片路径获取图片      NSData *data = UIImagePNGRepresentation(im);//获取图片数据               NSMutableData *imageData = [NSMutableData dataWithData:data];//ASIFormDataRequest 的setPostBody 方法需求的为NSMutableData类型      ASIFormDataRequest *aRequest = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:url]];      [aRequest setDelegate:delegate];//代理      [aRequest setRequestMethod:@"POST"];            [aRequest setPostBody:imageData];      [aRequest addRequestHeader:@"Content-Type" value:@"image/png"];//这里的value值 需与服务器端 一致            [aRequest startAsynchronous];//开始。异步        [aRequest setDidFinishSelector:@selector(headPortraitSuccess)];//当成功后会自动触发 headPortraitSuccess 方法      [aRequest setDidFailSelector:@selector(headPortraitFail)];//如果失败会 自动触发 headPortraitFail 方法