最近做項(xiàng)目中有個(gè)后臺(tái)api上傳文件、是要求使用multipart/form-data格式上傳文件托呕。
然后找了下資料含蓉,發(fā)現(xiàn)很少,是要用系統(tǒng)自帶網(wǎng)絡(luò)請(qǐng)求才能實(shí)現(xiàn)multipart/form-data格式上傳项郊,AFNet沒(méi)有這樣的api馅扣。也在網(wǎng)上找了些資料然后自己整合了一下
、着降、差油、
+(void)PostSubmitiphotoWithText:(NSString *)text name:(NSString *)name AppID:(NSString *)AppID Image:(NSData *)image twoname:(NSString *)twoname imageArray:(NSMutableArray *)imageArray filename:(NSString *)filename completionHandler:(void(^)(NSData *data, NSError *error))completion
{
NSURL *url = [NSURL URLWithString:@"http://app.hy-chip.com/hyChip3/feedback/information"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
//設(shè)置請(qǐng)求實(shí)體
NSMutableData *body = [NSMutableData data];
NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
NSString *time_now = [formatter stringFromDate:date];
NSString *nameID = @"5";
//4.設(shè)置請(qǐng)求體
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
text, @"content",
@"799610809@qq.com", @"contact",
time_now, @"time",
nameID, @"appId",
nil];
NSMutableDictionary *dictParmater = [NSMutableDictionary dictionaryWithObjectsAndKeys:
kAsign, @"sign",
@"1.4", @"ver",
params, @"params",
@"123456", @"id",
nil];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictParmater options:NSJSONWritingPrettyPrinted error:nil];
NSString*jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
NSRange range = {0,jsonString.length};
//去掉字符串中的空格
[mutStr replaceOccurrencesOfString:@"" withString:@"" options:NSLiteralSearch range:range];
NSRange range2 = {0,mutStr.length};
//去掉字符串中的換行符
[mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
//普通參數(shù)
[body appendData:[self getDataWithString:@"--BOUNDARY\r\n" ]];
//上傳參數(shù)需要key: (相應(yīng)參數(shù),在這里是_myModel.personID)
NSString *dispositions = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n",@"content"];
[body appendData:[self getDataWithString:dispositions ]];
[body appendData:[self getDataWithString:@"\r\n"]];
[body appendData:[self getDataWithString:mutStr]];
[body appendData:[self getDataWithString:@"\r\n"]];
for (int i = 0; i<imageArray.count-1; i++) {
//文件參數(shù)
UIImage * img = imageArray[i];
NSData *imageData = [NSData data];
NSString *imageFormat = @"";
imageFormat = @"Content-Type: image/jpeg \r\n";
imageData = UIImageJPEGRepresentation(img,0.6); //圖片壓縮
[body appendData:[self getDataWithString:@"--BOUNDARY\r\n" ]];
NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@.jpg\"\r\n",@"file",filename];
[body appendData:[self getDataWithString:disposition ]];
NSLog(@"%@___________",body);
[body appendData:[self getDataWithString:imageFormat]];
[body appendData:[self getDataWithString:@"\r\n"]];
[body appendData:imageData];
[body appendData:[self getDataWithString:@"\r\n"]];
}
//參數(shù)結(jié)束
[body appendData:[self getDataWithString:@"--BOUNDARY--\r\n"]];
request.HTTPBody = body;
//設(shè)置請(qǐng)求體長(zhǎng)度
NSInteger length = [body length];
[request setValue:[NSString stringWithFormat:@"%ld",length] forHTTPHeaderField:@"Content-Length"];
//設(shè)置 POST請(qǐng)求文件上傳
[request setValue:@"multipart/form-data; boundary=BOUNDARY" forHTTPHeaderField:@"Content-Type"];
NSOperationQueue *queue = [NSOperationQueue mainQueue];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { // 當(dāng)請(qǐng)求結(jié)束的時(shí)候調(diào)用
if (!data){
NSLog(@"返回?cái)?shù)據(jù)為空-%@",data);
return;
}
if (!connectionError) {
}
dispatch_async(dispatch_get_main_queue(), ^{
completion(data,connectionError);
});
}];
}
任洞、蓄喇、、
然后上傳事件里面直接調(diào)用交掏,參數(shù)最好和后臺(tái)人員溝通對(duì)比一下妆偏。
///
for(NSInteger i = 0; i < imagesArray.count-1; i++)
{
//取出單張圖片二進(jìn)制數(shù)據(jù)
imageData = imagesArray[i];
// imageData = [NSKeyedArchiver archivedDataWithRootObject:imagesArray[i]]; //上傳一張照片成功
//imageData = UIImagePNGRepresentation(imagesArray[i]);
// 上傳的參數(shù)名,在服務(wù)器端保存文件的文件夾名
Name = [NSString stringWithFormat:@"%@%ld", imageData, i+1];
NSLog(@"Name------------%@",Name);
// 上傳filename
fileName = [NSString stringWithFormat:@"%@.jpg", Name];
NSLog(@"fileName------------%@",fileName);
}
[THFunCloud PostSubmitiphotoWithText:self.textView.text name:@"799610809@qq.com"AppID:@"5"Image:imageData twoname:@"file"imageArray:imagesArray filename:fileName completionHandler:^(NSData *data, NSError *error){
if (!error) {
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSString *msg = [jsonDict objectForKey:@"msg"];
NSString *ret_code = [jsonDict objectForKey:@"code"];
NSLog(@"%d-----------",ret_code.intValue);
if (ret_code.intValue != 200) {
[SVProgressHUD showErrorWithStatus:msg];
[SVProgressHUD dismissWithDelay:2.0];
}else{
[SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"已上傳", nil)];
[SVProgressHUD dismissWithDelay:2.0];
[self.navigationController popViewControllerAnimated:YES];
}
NSString * str =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%s:返回?cái)?shù)據(jù)2222:%@",__func__,str);
}
}];
}
///
希望能幫助你們盅弛!