由于iOS無法通過html表單來上傳圖片空镜,因此想要上傳圖片,必須實(shí)現(xiàn)http請(qǐng)求洁灵,而不能像其他語言那樣通過html表單的post就能上傳房铭。
上傳圖片的http post請(qǐng)求的格式是這樣的:
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請(qǐng)求的編碼方式為multipart/form-data(上傳文件必須用這個(gè))。
boundary=AaB03x說明了AaB03x為分界線撤摸。比如 --AaB03x 就是一個(gè)分界線的意思
content-disposition: form-data; name="field1"
Hello Boris!
這句話聲明了請(qǐng)求中的一個(gè)字段的名稱毅桃,如field1? 以及字段的值,如Hello Boris!這里類似form表單中的中間的空行是必須的准夷。
不同的字段之間用分界線分開疾嗅,分界線需要單獨(dú)一行,如 --AaB03x--
分界線的下一行冕象,是下一個(gè)字段
content-disposition: form-data; name="pic"; filename="boris.png"
Content-Type: image/png
... contents of boris.png ...
--AaB03x--
這里聲明了變量pic代承,也就是我們要傳的文件,上傳文件的時(shí)候需要在后邊指定file name:filename="boris.png"
并且需要在下一行指定文件的格式:Content-Type: image/png
.. contents of boris.png ...? 這里是boris.png的二進(jìn)制內(nèi)容渐扮,如 <89504e47 0d0a1a0a 0000000d 49484452 000000b4 000000b4 08020000 00b2af91 65000020 00494441 5478012c dd79b724 6b7616f6 8c888c88 8c9c8733 55ddb1d5 6a0db486 06218401 ......
在http post請(qǐng)求的結(jié)尾论悴,需要有一個(gè)分界線,但是是前后都有--的:--AaB03x--
以上的這些格式墓律,是http的規(guī)范膀估,每個(gè)空行,空格都是必須的耻讽。
下邊是iOS的實(shí)現(xiàn)代碼:
//分界線的標(biāo)識(shí)符
NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
//根據(jù)url初始化request
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:10];
//分界線 --AaB03x
NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
//結(jié)束符 AaB03x--
NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
//要上傳的圖片
UIImage *image=[params objectForKey:@"pic"];
//得到圖片的data
NSData* data = UIImagePNGRepresentation(image);
//http body的字符串
NSMutableString *body=[[NSMutableString alloc]init];
//參數(shù)的集合的所有key的集合
NSArray *keys= [params allKeys];
//遍歷keys
for(int i=0;i<[keys count];i++)
{
//得到當(dāng)前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"];
//聲明結(jié)束符:--AaB03x--
NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
//聲明myRequestData具则,用來放入http body
NSMutableData *myRequestData=[NSMutableData data];
//將body字符串轉(zhuǎn)化為UTF8格式的二進(jìn)制
[myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
//將image的data加入
[myRequestData appendData:data];
//加入結(jié)束符--AaB03x--
[myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
//設(shè)置HTTPHeader中Content-Type的值
NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
//設(shè)置HTTPHeader
[request setValue:content forHTTPHeaderField:@"Content-Type"];
//設(shè)置Content-Length
[request setValue:[NSString stringWithFormat:@"%d", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];
//設(shè)置http body
[request setHTTPBody:myRequestData];
//http method
[request setHTTPMethod:@"POST"];
//建立連接,設(shè)置代理
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//設(shè)置接受response的data
if (conn) {
mResponseData = [[NSMutableData data] retain];
}
以上是直接方式向服務(wù)器中發(fā)送照片
接下來是通過afn方式上傳照片
// 上傳圖片??
? AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];? ?
?// 回復(fù)請(qǐng)求序列化, 不寫不會(huì)走成功的回調(diào)??
? manager.responseSerializer = [AFHTTPResponseSerializer serializer];? ?
?// 上傳圖片路徑? ??
NSString *urlString = [NSString stringWithFormat:@"%@UIController/upload.json?modelForder=iOSAppImage", InterfacePublicStr]; ? ?
[manager POST:urlString parameters:nil constructingBodyWithBlock:^(id_Nonnull formData) {
//校正上傳服務(wù)器照片的方向
UIImage * newImage = [self fixOrientation:image];
// 圖片轉(zhuǎn)換成NSData型
NSData *fileData = UIImageJPEGRepresentation(newImage, 0.3);
// 服務(wù)器對(duì)應(yīng)的名字
NSString *file = @"file";
// 在網(wǎng)絡(luò)開發(fā)中具帮,上傳文件時(shí)博肋,是文件不允許被覆蓋低斋,文件重名 ? ? ? ?
// 要解決此問題,
// 可以在上傳時(shí)使用當(dāng)前的系統(tǒng)事件作為文件名
// 本機(jī)生成的圖片文件名
//該過程中獲取的GUID是一種由算法生成的二進(jìn)制長(zhǎng)度為128位的數(shù)字標(biāo)識(shí)符匪凡,也算是一種隨機(jī)數(shù)膊畴,給用來給照片起名字用的,為了讓圖片的名字不重復(fù)
NSString *filename = [NSString stringWithFormat:@"%@%@", [RequestPostUploadHelper generateUuidString], @".jpg"];
// 圖片類型
NSString *mineType = @"image/jpeg";
// 圖片上傳到服務(wù)器
appendPartWithFileData? ? ? ? ? 1. 要上傳的[二進(jìn)制數(shù)據(jù)]
name ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?2. 對(duì)應(yīng)網(wǎng)站上[upload.php中]處理文件的[字段"file"]/后臺(tái)給的該照片在服務(wù)器中對(duì)應(yīng)的的字段名字
fileName ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 3. 要保存在服務(wù)器上的[文件名]
mimeType ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?4. 上傳文件的[mimeType]
[formData appendPartWithFileData:fileData name:file fileName:filename mimeType:mineType];
} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id? _Nullable responseObject) {
// 返回的NSData轉(zhuǎn)換成字典
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:@"由于網(wǎng)絡(luò)原因, 上傳失敗!"];
}];
//獲取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;
}