AF 对咱们开发者来说并不陌生,今天要说的就是如何利用af来上传图片以及语音文件:(注:af 可以去github下载)
其实af可以进行二次分装今天就先不谈分装直接用af原生库上传。
1.首先导入
#import "AFNetworking.h"
2.代码
AFHTTPRequestOperationManager * mager=[AFHTTPRequestOperationManager manager];
//设置相应内容类型
mager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
//设置延迟时间
mager.requestSerializer.timeoutInterval = 30;
//参数(1)url:服务器接口 (2)params 参数传递(可以为空)(3)self.choosePicShow.mainArray (上传的图片数组)
[mager POST:url parameters:params constructingBodyWithBlock:^(idformData) {
for(NSInteger i = 0; i < self.choosePicShow.mainArray.count; i++){
UIImageView * imageView = [self.choosePicShow.mainArray objectAtIndex:i];
UIImage* image = imageView.image;
NSData* imageData = UIImageJPEGRepresentation(image, 0);//转化为二进制数据上传服务器
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.png", str];//时间格式命名图片避免名字重复
[formData appendPartWithFileData:imageData name:@"file[]" fileName:fileName mimeType:@"image/jpeg"];
}
//语音文件上传
NSString * paths =mp3SavePath;
NSLog(@"----上传文件路径-----%@",paths);
NSData * Sounddata=[NSData dataWithContentsOfFile:paths];//同样转化二进制数据上传
[formData appendPartWithFileData:Sounddata name:@"sounds" fileName:@"l23.mp3" mimeType:@"amr/mp3/wmr"];
} success:^(AFHTTPRequestOperation *operation, NSDictionary *statusDict) {// statusDict上传成功服务返回的数据
NSLog(@"success=%@",statusDict);
int code=[[statusDict valueForKey:@"code"]intValue];
if(code==1){
[LSXother ShowMBProgressHUDWithTitle:@"上传成功!" andImageNmae:nil addView:self.view];
[self.navigationController popViewControllerAnimated:YES];
}else{
[LSXother ShowMBProgressHUDWithTitle:@"上传失败!" andImageNmae:nil addView:self.view];
}
[SVProgressHUD dismiss];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"success=%@",error);
[SVProgressHUD dismiss];
[LSXother ShowMBProgressHUDWithTitle:@"网络超时,请稍候重试!" andImageNmae:nil addView:self.view];
}];
以上就是上传的代码如有错误和不足希望指出,我会进一步改进谢谢!