最近做项目中有个后台api上传文件、是要求使用multipart/form-data格式上传文件。
然后找了下资料,发现很少,是要用系统自带网络请求才能实现multipart/form-data格式上传,AFNet没有这样的api。也在网上找了些资料然后自己整合了一下
、、、
+(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";
//设置请求实体
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.设置请求体
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];
//普通参数
[body appendData:[self getDataWithString:@"--BOUNDARY\r\n" ]];
//上传参数需要key: (相应参数,在这里是_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++) {
//文件参数
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"]];
}
//参数结束
[body appendData:[self getDataWithString:@"--BOUNDARY--\r\n"]];
request.HTTPBody = body;
//设置请求体长度
NSInteger length = [body length];
[request setValue:[NSString stringWithFormat:@"%ld",length] forHTTPHeaderField:@"Content-Length"];
//设置 POST请求文件上传
[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) { // 当请求结束的时候调用
if (!data){
NSLog(@"返回数据为空-%@",data);
return;
}
if (!connectionError) {
}
dispatch_async(dispatch_get_main_queue(), ^{
completion(data,connectionError);
});
}];
}
、、、
然后上传事件里面直接调用,参数最好和后台人员沟通对比一下。
///
for(NSInteger i = 0; i < imagesArray.count-1; i++)
{
//取出单张图片二进制数据
imageData = imagesArray[i];
// imageData = [NSKeyedArchiver archivedDataWithRootObject:imagesArray[i]]; //上传一张照片成功
//imageData = UIImagePNGRepresentation(imagesArray[i]);
// 上传的参数名,在服务器端保存文件的文件夹名
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:返回数据2222:%@",__func__,str);
}
}];
}
///
希望能帮助你们!