使用AFNetWorking上传图片
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSString *string = @"admin:100";
NSData *originData = [string dataUsingEncoding:NSASCIIStringEncoding];
NSString *encodeResult = [originData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
NSString *end = [NSString stringWithFormat:@"Basic %@",encodeResult];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
@"text/html",
@"image/jpeg",
@"image/png",
@"application/octet-stream",
@"text/json",
nil];
[manager.requestSerializer setValue:end forHTTPHeaderField:@"Authorization"];
[manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
NSString *urlStr = [NSString stringWithFormat:@"%@%@",kNetIp,Net_UploadImg];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
NSLog(@" 上传图片请求参数 url %@ %@ manager %@",urlStr,parameters,manager.requestSerializer.HTTPRequestHeaders);
[manager POST:urlStr parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData)
{
// 上传文件
NSData *imageData;
if (UIImagePNGRepresentation(_pickedImg) == nil)
{
imageData = UIImageJPEGRepresentation(_pickedImg, 1);
}
else
{
imageData = UIImagePNGRepresentation(_pickedImg);
}
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
//上传的参数(上传图片,以文件流的格式)
[formData appendPartWithFileData:imageData
name:@"file"
fileName:fileName
mimeType:@"image/jpeg"];
}
progress:^(NSProgress *_Nonnull uploadProgress)
{
//打印下上传进度
}
success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject)
{
//上传成功
}
failure:^(NSURLSessionDataTask *_Nullable task, NSError * _Nonnull error)
{
//上传失败
NSError *code = (NSError *)error;
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"图片上传出错" message:[NSString stringWithFormat:@"%@",code.localizedDescription] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert show];
}];