iOS里实现multipart/form-data格式上传文件(多图上传,文件参数,其他参数)

最近做项目中有个后台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",
                                @"[email protected]",        @"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

}
、、、

然后上传事件里面直接调用,参数最好和后台人员沟通对比一下。
///
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:@"[email protected]"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);
        }
    }];
    
}

///

希望能帮助你们!

你可能感兴趣的:(iOS里实现multipart/form-data格式上传文件(多图上传,文件参数,其他参数))