由于iOS无法通过html表单来上传图片,因此想要上传图片,必须实现http请求,而不能像其他语言那样通过html表单的post就能上传,做单图上传时参考网上的例子可以实现,但是发现网上的例子不支持多张上传,所以自己仿照单图的格式写了一个多图上传的。其实只要格式拼接正确就可以实现多图上传的功能。
.h文件实现
#import <Foundation/Foundation.h>
@interface PicUpload : NSObject
+ (NSString *)postRequestWithURL: (NSString *)url // IN
postParems: (NSMutableDictionary *)postParems // IN
picFilePath: (NSMutableArray *)picFilePath // IN
picFileName: (NSMutableArray *)picFileName ;
@end
.m文件实现
// Copyright (c) 2014年 Clover. All rights reserved.
#import "PicUpload.h"
#import "SVProgressHUD.h"
#import "SBJson.h"
#import "Singleton.h"
@implementation PicUpload
static NSString * const FORM_FLE_INPUT = @"file1";
+ (NSString *)postRequestWithURL: (NSString *)url
postParems: (NSMutableDictionary *)postParems
picFilePath: (NSMutableArray *)picFilePath
picFileName: (NSMutableArray *)picFileName
{
NSString *hyphens = @"--";
NSString *boundary = @"*****";
NSString *end = @"\r\n";
NSMutableData *myRequestData1=[NSMutableData data];
//遍历数组,添加多张图片
for (int i = 0; i < picFilePath.count; i ++) {
NSData* data;
UIImage *image=[UIImage imageWithContentsOfFile:[picFilePath objectAtIndex:i]];
//判断图片是不是png格式的文件
if (UIImagePNGRepresentation(image)) {
//返回为png图像。
data = UIImagePNGRepresentation(image);
}else {
//返回为JPEG图像。
data = UIImageJPEGRepresentation(image, 1.0);
}
//所有字段的拼接都不能缺少,要保证格式正确
[myRequestData1 appendData:[hyphens dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData1 appendData:[boundary dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData1 appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableString *fileTitle=[[NSMutableString alloc]init];
//要上传的文件名和key,服务器端用file接收
[fileTitle appendFormat:@"Content-Disposition:form-data;name=\"%@\";filename=\"%@\"",[NSString stringWithFormat:@"file%d",i+1],[NSString stringWithFormat:@"image%d.png",i+1]];
[fileTitle appendString:end];
[fileTitle appendString:[NSString stringWithFormat:@"Content-Type:application/octet-stream%@",end]];
[fileTitle appendString:end];
[myRequestData1 appendData:[fileTitle dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData1 appendData:data];
[myRequestData1 appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
}
[myRequestData1 appendData:[hyphens dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData1 appendData:[boundary dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData1 appendData:[hyphens dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData1 appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
//参数的集合的所有key的集合
NSArray *keys= [postParems allKeys];
//添加其他参数
for(int i=0;i<[keys count];i++)
{
NSMutableString *body=[[NSMutableString alloc]init];
[body appendString:hyphens];
[body appendString:boundary];
[body appendString:end];
//得到当前key
NSString *key=[keys objectAtIndex:i];
//添加字段名称
[body appendFormat:@"Content-Disposition: form-data; name=\"%@\"",key];
[body appendString:end];
[body appendString:end];
//添加字段的值
[body appendFormat:@"%@",[postParems objectForKey:key]];
[body appendString:end];
[myRequestData1 appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"添加字段的值==%@",[postParems objectForKey:key]);
}
//根据url初始化request
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:20];
//设置HTTPHeader中Content-Type的值
NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",boundary];
//设置HTTPHeader
[request setValue:content forHTTPHeaderField:@"Content-Type"];
//设置Content-Length
[request setValue:[NSString stringWithFormat:@"%d", [myRequestData1 length]] forHTTPHeaderField:@"Content-Length"];
//设置http body
[request setHTTPBody:myRequestData1];
//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);
SBJsonParser *parser = [[SBJsonParser alloc ] init];
NSDictionary *jsonobj = [parser objectWithString:result];
if (jsonobj == nil || (id)jsonobj == [NSNull null] || [[jsonobj objectForKey:@"flag"] intValue] == 0)
{
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"提交失败." delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alert show];
});
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"提交成功." delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[Singleton sharedSingleton].shopId = [[jsonobj objectForKey:@"shopId"]stringValue];
[alert show];
});
}
return result;
}
else if (error) {
NSLog(@"%@",error);
[[NSNotificationCenter defaultCenter]postNotificationName:@"dissmissSVP" object:nil];
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"提交失败." delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alert show];
return nil;
}
else
return nil;
}
@end
在需要上传图片的界面使用如下代码调用该上传类:使用时根据需要进行相应调整就可以。
[SVProgressHUD showWithStatus:@"上传中,请稍候..." maskType:SVProgressHUDMaskTypeClear];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSMutableDictionary * dir=[NSMutableDictionary dictionaryWithCapacity:7];
//像字典添加除图片之外的相关参数
[dir setValue:@"0" forKey:@"longitude"];
[dir setValue:@"0" forKey:@"latitude"];
NSString *url = [NSString stringWithFormat:@"%@ShopManage-addStore",OA_DOMAIN];
NSLog(@"有图片上传");
//<span style="font-family: Helvetica, Tahoma, Arial, sans-serif;">self.pathArray存储要被上传的图片的路径,</span><span style="font-family: Helvetica, Tahoma, Arial, sans-serif;">self.nameArray存储要被上传的图片的名称</span>
[PicUpload postRequestWithURL:url postParems:dir picFilePath:self.pathArray picFileName:self.nameArray];
});
相关代码下载地址:http://download.csdn.net/detail/u011918080/6947253
最近在写新的项目,对上传图片的方法有些修改
- (void)httpRequestWithRequest:(CMCMHttpRequest *)httpRequest
url:(NSString *)urlStr
imageArray:(NSMutableArray *)imageArray
postParems:(NSDictionary *)postParems
errorBlock:(ErrorBlock)error
finshedBlock:(RequestFinishBlock)finish
{
NSLog(@"urlStr=%@",urlStr);
httpRequest.finishBlock = finish;
httpRequest.errorBlock = error;
NSString *hyphens = @"--";
NSString *boundary = @"*****";
NSString *end = @"\r\n";
NSMutableData *myRequestData1 = [NSMutableData data];
//参数的集合的所有key的集合
NSArray *keys= [postParems allKeys];
//添加其他参数
for(int i = 0;i < [keys count];i ++)
{
NSMutableString *body = [[NSMutableString alloc]init];
[body appendString:hyphens];
[body appendString:boundary];
[body appendString:end];
//得到当前key
NSString *key = [keys objectAtIndex:i];
//添加字段名称
[body appendFormat:@"Content-Disposition: form-data; name=\"%@\"%@%@",key,end,end];
//添加字段的值
[body appendFormat:@"%@",[postParems objectForKey:key]];
[body appendString:end];
[myRequestData1 appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"添加字段的值==%@",[postParems objectForKey:key]);
}
//遍历数组,添加多张图片
for (int i = 0; i < imageArray.count; i ++) {
NSData* data;
NSDictionary *dict = imageArray[i];
UIImage *image = dict[UIImagePickerControllerOriginalImage];
// //判断图片是不是png格式的文件
// if (UIImagePNGRepresentation(image)) {
// //返回为png图像。
// data = UIImagePNGRepresentation(image);
// }else {
//返回为JPEG图像。
data = UIImageJPEGRepresentation(image, 0.1);
// }
//所有字段的拼接都不能缺少,要保证格式正确
[myRequestData1 appendData:[hyphens dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData1 appendData:[boundary dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData1 appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableString *fileTitle = [[NSMutableString alloc]init];
//要上传的文件名和key,服务器端用file接收
[fileTitle appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"%@",@"pic",end];
[fileTitle appendString:[NSString stringWithFormat:@"Content-Type:image/jpeg%@%@",end,end]];
[myRequestData1 appendData:[fileTitle dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData1 appendData:data];
[myRequestData1 appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
}
[myRequestData1 appendData:[hyphens dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData1 appendData:[boundary dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData1 appendData:[hyphens dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData1 appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
//根据url初始化request
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:CMCM_TIME_OUT];
//http method
[request setHTTPMethod:@"POST"];
//设置HTTPHeader中Content-Type的值
NSString *content = [[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",boundary];
//设置HTTPHeader
[request setValue:content forHTTPHeaderField:@"Content-Type"];
//设置Content-Length
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData1 length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
//设置http body
[request setHTTPBody:myRequestData1];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:httpRequest];
[connection start];
}