使用AFNetworking的方法
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];//初始化请求对象
manager.responseSerializer = [AFHTTPResponseSerializer serializer];//设置服务器允许的请求格式内容
// manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json", @"text/javascript,multipart/form-data", nil];
//上传图片/文字,只能同POST
[manager POST:kUploadAvatarURL parameters:@{@"user_id":@"1000665",@"sign_key":@"566e37eadb8fa4794f8415db11d828f3"} constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
// 注意:这个name(我的后台给的字段是file)一定要和后台的参数字段一样 否则不成功
[formData appendPartWithFileData:data name:@"file" fileName:@"aaa.jpg" mimeType:@"image/jpg"];
// [formData appendPartWithFormData:[@"wfWiEWrgEFA9A78512weF7106A" dataUsingEncoding:NSUTF8StringEncoding]
name:@"aaa"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(@"uploadProgress = %@",uploadProgress);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"responseObject = %@, task = %@",responseObject,task);
NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
NSLog(@"obj = %@",obj[@"error_msg"]);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error = %@",error);
}];
还有一个是网上搜到的别人封装的类
RequestPostUploadHelper.h文件
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface RequestPostUploadHelper : NSObject
/**
*POST 提交 并可以上传图片目前只支持单张
*/
+ (NSString *)postRequestWithURL: (NSString *)url // IN
postParems: (NSMutableDictionary *)postParems // IN 提交参数据集合
picFilePath: (NSString *)picFilePath // IN 上传图片路径
picFileName: (NSString *)picFileName; // IN 上传图片名称
/**
* 修发图片大小
*/
+ (UIImage *) imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize) newSize;
/**
* 保存图片
*/
+ (NSString *)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName;
/**
* 生成GUID
*/
//+ (NSString *)generateUuidString;
@end
RequestPostUploadHelper.m文件
注意:这个文件里面需要修改static NSString * const FORM_FLE_INPUT = @"file"; 把file修改为你后台规定的字段,否则不会成功
#import "RequestPostUploadHelper.h"
@implementation RequestPostUploadHelper
static NSString * const FORM_FLE_INPUT = @"file";//与服务器要求的key 一样
+ (NSString *)postRequestWithURL: (NSString *)url // IN
postParems: (NSMutableDictionary *)postParems // IN
picFilePath: (NSString *)picFilePath // IN上传图片路径
picFileName: (NSString *)picFileName // IN
{
NSString *TWITTERFON_FORM_BOUNDARY = @"0xKhTmLbOuNdArY";
//根据url初始化request
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:10];
//分界线 --AaB03x
NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
//结束符 AaB03x--
NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
//得到图片的data
NSData* data;
if(picFilePath){
UIImage *image=[UIImage imageWithContentsOfFile:picFilePath];
//判断图片是不是png格式的文件
if (UIImagePNGRepresentation(image)) {
//返回为png图像。
data = UIImagePNGRepresentation(image);
}else {
//返回为JPEG图像。
data = UIImageJPEGRepresentation(image, 1.0);
}
}
//http body的字符串
NSMutableString *body=[[NSMutableString alloc]init];
//参数的集合的所有key的集合
NSArray *keys= [postParems allKeys];
//遍历keys
for(int i=0;i<[keys count];i++)
{
//得到当前key
NSString *key=[keys objectAtIndex:i];
//添加分界线,换行
[body appendFormat:@"%@\r\n",MPboundary];
//添加字段名称,换2行
[body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
//添加字段的值
[body appendFormat:@"%@\r\n",[postParems objectForKey:key]];
NSLog(@"添加字段的值==%@",[postParems objectForKey:key]);
}
if(picFilePath){
////添加分界线,换行
[body appendFormat:@"%@\r\n",MPboundary];
//声明pic字段,文件名为boris.png
[body appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",FORM_FLE_INPUT,picFileName];
//声明上传文件的格式
[body appendFormat:@"Content-Type: image/jpge,image/gif, image/jpeg, image/pjpeg, image/pjpeg\r\n\r\n"];
NSLog(@"body = %@",body);
}
//声明结束符:--AaB03x--
NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
//声明myRequestData,用来放入http body
NSMutableData *myRequestData=[NSMutableData data];
//将body字符串转化为UTF8格式的二进制
[myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
if(picFilePath){
//将image的data加入
[myRequestData appendData:data];
}
//加入结束符--AaB03x--
[myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
//设置HTTPHeader中Content-Type的值
NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
//设置HTTPHeader
[request setValue:content forHTTPHeaderField:@"Content-Type"];
//设置Content-Length
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
//设置http body
[request setHTTPBody:myRequestData];
//http method
[request setHTTPMethod:@"POST"];
NSHTTPURLResponse *urlResponese = nil;
NSError *error = [[NSError alloc]init];
NSData* resultData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponese error:&error];
NSString* result= [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
if([urlResponese statusCode] >=200&&[urlResponese statusCode]<300){
NSLog(@"返回结果=====%@",result);
return result;
}
return nil;
}
/**
* 修发图片大小
*/
+ (UIImage *) imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize) newSize{
newSize.height=image.size.height*(newSize.width/image.size.width);
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
/**
* 保存图片
*/
+ (NSString *)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName{
NSData* imageData;
//判断图片是不是png格式的文件
if (UIImagePNGRepresentation(tempImage)) {
//返回为png图像。
imageData = UIImagePNGRepresentation(tempImage);
}else {
//返回为JPEG图像。
imageData = UIImageJPEGRepresentation(tempImage, 1.0);
}
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
NSArray *nameAry=[fullPathToFile componentsSeparatedByString:@"/"];
NSLog(@"===fullPathToFile===%@",fullPathToFile);
NSLog(@"===FileName===%@",[nameAry objectAtIndex:[nameAry count]-1]);
[imageData writeToFile:fullPathToFile atomically:NO];
return fullPathToFile;
}
///**
// * 生成GUID
// */
//+ (NSString *)generateUuidString{
// // create a new UUID which you own
// CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
//
// // create a new CFStringRef (toll-free bridged to NSString)
// // that you own
// NSString *uuidString = (NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuid);
//
// // transfer ownership of the string
// // to the autorelease pool
// [uuidString autorelease];
//
// // release the UUID
// CFRelease(uuid);
//
// return uuidString;
//}
@end
.m文件中调用类方法
NSString *picString = [RequestPostUploadHelper saveImage:littleImg WithName:@"avatar.jpg"];
NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setObject:[UserLoginStateManager shareManager].model.userID forKey:@"user_id"];
[params setObject:[UserLoginStateManager shareManager].model.sign_key forKey:@"sign_key"];
[RequestPostUploadHelper postRequestWithURL:kUploadAvatarURL postParems:params picFilePath:picString picFileName:@"avatar.jpg"];