iOS Multipart上传单张图片

#pragma mark - uploadFile
- (void)uploadFile:(NSDictionary *)dic {
   
    NSURL *URL = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"%@addVisitRecord",SERVER_ADDRESS]];
    request = [[NSMutableURLRequest alloc] initWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    NSString *boundary = @"wfWiEWrgEFA9A78512weF7106A";
    request.HTTPMethod = @"POST";
    request.allHTTPHeaderFields = @{@"Content-Type":[NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]};
    //multipart/form-data格式按照构建上传数据
    NSMutableData *postData = [[NSMutableData alloc] init];
    for (NSString *key in dic) {
        NSString *pair = [NSString stringWithFormat:@"--%@ Content-Disposition: form-data; name="%@" ",boundary,key];
        [postData appendData:[pair dataUsingEncoding:NSUTF8StringEncoding]];
       
        id value = [dic objectForKey:key];
        if ([value isKindOfClass:[NSString class]]) {
            [postData appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
        } else if ([value isKindOfClass:[NSData class]]){
            [postData appendData:value];
        }
        [postData appendData:[@" " dataUsingEncoding:NSUTF8StringEncoding]];
    }
    //文件部分
    NSString *filename = [filePath lastPathComponent];
    NSString *contentType = AFContentTypeForPathExtension([filePath pathExtension]);
   
    NSString *filePair = [NSString stringWithFormat:@"--%@ Content-Disposition: form-data; name="%@"; filename="%@";Content-Type=%@ ",boundary,@"img",filename,contentType];
    [postData appendData:[filePair dataUsingEncoding:NSUTF8StringEncoding]];
   
    [postData appendData:self.imageSecondFile]; //加入文件的数据
   
    [postData appendData:[[NSString stringWithFormat:@" --%@-- ",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    request.HTTPBody = postData;
    [request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)postData.length] forHTTPHeaderField:@"Content-Length"];
    _connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [_connection start];
}
#pragma mark - connection delegate
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"reveive Response: %@",response);
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    if (!_reveivedData) {
        _reveivedData = [[NSMutableData alloc]init];
    }
    [_reveivedData appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    [[CRMDatahandle shareDataHandle] saveLocalData:@"REFRESH_PLAY" value:@"YES"];
    NSError *err;
    NSDictionary *note = [NSJSONSerialization JSONObjectWithData:_reveivedData  options:NSJSONReadingMutableContainers error:&err];
    if ([note[@"success"] integerValue] == 1) {
        [CRMDatahandle hudWithText:@"添加成功!" atView:self.view];
        [[IQKeyboardManager sharedManager] setEnable:NO];
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(succesPaly) userInfo:nil repeats:NO];
    }
  
}
原文地址:https://www.cnblogs.com/tian-sun/p/5909930.html