http post方式上传照片

由于iOS无法通过html表单来上传图片,因此想要上传图片,必须实现http请求,而不能像其他语言那样通过html表单的post就能上传。

上传图片的http post请求的格式是这样的:

Content-type: multipart/form-data, boundary=AaB03x

--AaB03x

content-disposition: form-data; name="field1"

Hello Boris!

--AaB03x

content-disposition: form-data; name="pic"; filename="boris.png"

Content-Type: image/png

... contents of boris.png ...

--AaB03x--

第一行是指定了http post请求的编码方式为multipart/form-data(上传文件必须用这个)。

boundary=AaB03x说明了AaB03x为分界线。比如 --AaB03x 就是一个分界线的意思

content-disposition: form-data; name="field1"

Hello Boris!

这句话声明了请求中的一个字段的名称,如field1  以及字段的值,如Hello Boris!这里类似form表单中的中间的空行是必须的。

不同的字段之间用分界线分开,分界线需要单独一行,如 --AaB03x--

分界线的下一行,是下一个字段

content-disposition: form-data; name="pic"; filename="boris.png"

Content-Type: image/png

... contents of boris.png ...

--AaB03x--

这里声明了变量pic,也就是我们要传的文件,上传文件的时候需要在后边指定file name:filename="boris.png"

并且需要在下一行指定文件的格式:Content-Type: image/png

.. contents of boris.png ...  这里是boris.png的二进制内容,如 <89504e47 0d0a1a0a 0000000d 49484452 000000b4 000000b4 08020000 00b2af91 65000020 00494441 5478012c dd79b724 6b7616f6 8c888c88 8c9c8733 55ddb1d5 6a0db486 06218401 ......

在http post请求的结尾,需要有一个分界线,但是是前后都有--的:--AaB03x--

以上的这些格式,是http的规范,每个空行,空格都是必须的。

下边是iOS的实现代码:

//分界线的标识符

NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";

//根据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];

//要上传的图片

UIImage *image=[params objectForKey:@"pic"];

//得到图片的data

NSData* data = UIImagePNGRepresentation(image);

//http body的字符串

NSMutableString *body=[[NSMutableString alloc]init];

//参数的集合的所有key的集合

NSArray *keys= [params allKeys];

//遍历keys

for(int i=0;i<[keys count];i++)

{

//得到当前key

NSString *key=[keys objectAtIndex:i];

//如果key不是pic,说明value是字符类型,比如name:Boris

if(![key isEqualToString:@"pic"])

{

//添加分界线,换行

[body appendFormat:@"%@\r\n",MPboundary];

//添加字段名称,换2行

[body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];

//添加字段的值

[body appendFormat:@"%@\r\n",[params objectForKey:key]];

}

}

////添加分界线,换行

[body appendFormat:@"%@\r\n",MPboundary];

//声明pic字段,文件名为boris.png

[body appendFormat:@"Content-Disposition: form-data; name=\"pic\"; filename=\"boris.png\"\r\n"];

//声明上传文件的格式

[body appendFormat:@"Content-Type: image/png\r\n\r\n"];

//声明结束符:--AaB03x--

NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];

//声明myRequestData,用来放入http body

NSMutableData *myRequestData=[NSMutableData data];

//将body字符串转化为UTF8格式的二进制

[myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];

//将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:@"%d", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];

//设置http body

[request setHTTPBody:myRequestData];

//http method

[request setHTTPMethod:@"POST"];

//建立连接,设置代理

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

//设置接受response的data

if (conn) {

mResponseData = [[NSMutableData data] retain];

}

以上是直接方式向服务器中发送照片




接下来是通过afn方式上传照片

// 上传图片  

  AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];   

 // 回复请求序列化, 不写不会走成功的回调  

  manager.responseSerializer = [AFHTTPResponseSerializer serializer];   

 // 上传图片路径    

NSString *urlString = [NSString stringWithFormat:@"%@UIController/upload.json?modelForder=iOSAppImage", InterfacePublicStr];    

[manager POST:urlString parameters:nil constructingBodyWithBlock:^(id_Nonnull formData) {

//校正上传服务器照片的方向

UIImage * newImage = [self fixOrientation:image];

// 图片转换成NSData型

NSData *fileData = UIImageJPEGRepresentation(newImage, 0.3);

// 服务器对应的名字

NSString *file = @"file";

// 在网络开发中,上传文件时,是文件不允许被覆盖,文件重名        

// 要解决此问题,

// 可以在上传时使用当前的系统事件作为文件名

// 本机生成的图片文件名

//该过程中获取的GUID是一种由算法生成的二进制长度为128位的数字标识符,也算是一种随机数,给用来给照片起名字用的,为了让图片的名字不重复

NSString *filename = [NSString stringWithFormat:@"%@%@", [RequestPostUploadHelper generateUuidString], @".jpg"];


// 图片类型

NSString *mineType = @"image/jpeg";

// 图片上传到服务器

appendPartWithFileData          1. 要上传的[二进制数据]

name                                      2. 对应网站上[upload.php中]处理文件的[字段"file"]/后台给的该照片在服务器中对应的的字段名字

fileName                                 3. 要保存在服务器上的[文件名]

mimeType                              4. 上传文件的[mimeType]


[formData appendPartWithFileData:fileData name:file fileName:filename mimeType:mineType];

} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

// 返回的NSData转换成字典

NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];

[MBProgressHUD hideHUD];

if ([[jsonDict allKeys] containsObject:@"opfileupload"])

{

[MBProgressHUD showSuccess:@"上传成功!"];

}

else

{

[MBProgressHUD showError:@"上传失败!"];

}

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

[MBProgressHUD hideHUD];

[MBProgressHUD showError:@"由于网络原因, 上传失败!"];

}];



//获取GUID的方法

/**

* 生成GUID

*/

+ (NSString *)generateUuidString{

// create a new UUID which you own

CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);

//NSString *uuidString = (NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuid);

NSString *uuidString = (NSString *)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuid));

CFRelease(uuid);

return uuidString;

}


//让图片的方向始终为竖着的方法

-(UIImage *)fixOrientation:(UIImage *)aImage {

if (aImage.imageOrientation == UIImageOrientationUp)

return aImage;

CGAffineTransform transform = CGAffineTransformIdentity;

switch (aImage.imageOrientation) {

case UIImageOrientationDown:

case UIImageOrientationDownMirrored:

transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);

transform = CGAffineTransformRotate(transform, M_PI);

break;

case UIImageOrientationLeft:

case UIImageOrientationLeftMirrored:

transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);

transform = CGAffineTransformRotate(transform, M_PI_2);

break;

case UIImageOrientationRight:

case UIImageOrientationRightMirrored:

transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);

transform = CGAffineTransformRotate(transform, -M_PI_2);

break;

default:

break;

}

switch (aImage.imageOrientation) {

case UIImageOrientationUpMirrored:

case UIImageOrientationDownMirrored:

transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);

transform = CGAffineTransformScale(transform, -1, 1);

break;

case UIImageOrientationLeftMirrored:

case UIImageOrientationRightMirrored:

transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);

transform = CGAffineTransformScale(transform, -1, 1);

break;

default:

break;

}

CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,

CGImageGetBitsPerComponent(aImage.CGImage), 0,

CGImageGetColorSpace(aImage.CGImage),

CGImageGetBitmapInfo(aImage.CGImage));

CGContextConcatCTM(ctx, transform);

switch (aImage.imageOrientation) {

case UIImageOrientationLeft:

case UIImageOrientationLeftMirrored:

case UIImageOrientationRight:

case UIImageOrientationRightMirrored:

// Grr...

CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);

break;

default:

CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);

break;

}

CGImageRef cgimg = CGBitmapContextCreateImage(ctx);

UIImage *img = [UIImage imageWithCGImage:cgimg];

CGContextRelease(ctx);

CGImageRelease(cgimg);

return img;

}

你可能感兴趣的:(http post方式上传照片)