您的位置:首页 > 产品设计 > UI/UE

ios ASIFormDataRequest上传图片到php服务器

2015-12-24 14:38 513 查看
现在ASI这个库已经很少使用了 但是还有部分公司的项目会用到,下面展示一下我写项目时用到的上传图片案例

首先这个库用到的依赖我就不说了,要导入#import " ASIFormDataRequest.h"这个头文件:

-(void)postTeacherNotice{

UIImage *im =_upImage;//通过path图片路径获取图片

NSData *data =UIImagePNGRepresentation(im);//获取图片数据
/*

ios中获取图片的方法有两种,一种是UIImageJPEGRepresentation,一种是UIImagePNGRepresentation

前者获取到图片的数据量要比后者的小很多。。

*/

NSMutableData *imageData = [NSMutableDatadataWithData:data];//ASIFormDataRequest的setPostBody
方法需求的为NSMutableData类型

NSURL *url = [NSURLURLWithString:@"http://xxxxxxxxxxxxxxx"];

ASIFormDataRequest *aRequest = [[ASIFormDataRequestalloc]
initWithURL:url];
[aRequestsetDelegate:self];//代理

//设置请求类型
[aRequestsetRequestMethod:@"POST"];

[aRequestsetPostValue:restypeStr
forKey:@"restype"];

[aRequestsetPostValue:_logonUser.schoolCodeforKey:@"schoolcode"];
[aRequestsetPostValue:_logonUser.userCodeforKey:@"sendcode"];

[aRequestsetPostValue:self.recvcodeforKey:@"recvcode"];
[aRequestsetPostValue:recvtypeStr
forKey:@"recvtype"];

[aRequestaddData:imageData
withFileName:[NSString
stringWithFormat:@"%d.png",arc4random()]andContentType:@"image/png"forKey:@"file"];

/*此处也可以不写

NSString *content=[[NSStringalloc]initWithFormat:@"multipart/form-data; boundary=%@",@"randomIDStr"];
[aRequestaddRequestHeader:@"Content-Type"value:content];<span style="font-family: Menlo;">//</span><span style="font-family: 'Heiti SC Light';">这里的</span><span style="font-family: Menlo;">value</span><span style="font-family: 'Heiti SC Light';">值</span><span style="font-family: 'Heiti SC Light';">需与服务器端</span><span style="font-family: 'Heiti SC Light';">一致</span>


*/

[aRequest startAsynchronous];//开始。异步
[aRequestsetDidFinishSelector:@selector(headPortraitSuccess:)];//当成功后会自动触发
headPortraitSuccess 方法
[aRequestsetDidFailSelector:@selector(headPortraitFail:)];//如果失败会自动触发
headPortraitFail方法

}
-(void)headPortraitSuccess:(ASIHTTPRequest *)request{
NSString *responseString = [request
responseString];

NSArray *arry=[responseString
componentsSeparatedByString:@"\":"];

NSArray *arry1=[arry[1]componentsSeparatedByString:@","];
int Result =[arry1[0]intValue];
if (Result>0) {

UIAlertView *alert = [[UIAlertViewalloc]
initWithTitle:@"提示"message:@"通知发送成功"delegate:selfcancelButtonTitle:@"取消"otherButtonTitles:@"确定",nil];
[alertshow];
NSLog(@"发送成功%d",Result);
}

[self.navigationControllerpopViewControllerAnimated:YES];
}
-(void)headPortraitFail:(ASIHTTPRequest *)request{
NSString *responseString = [request
responseString];
NSLog(@"发送失败%@",responseString);

UIAlertView *alert = [[UIAlertViewalloc]
initWithTitle:@"提示"message:@"通知发送失败"delegate:selfcancelButtonTitle:@"取消"otherButtonTitles:@"确定",nil];
[alertshow];

[self.navigationControllerpopViewControllerAnimated:YES];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: