iOS 提交form表单,上传图片

之前不会用,总感觉很难,用后感觉不是太难,本文只是简单的讲一下怎么使用的,

//实例话对象
 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 20;
    manager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    
    //在请求头里 添加自己需要的参数
    NSString *token = [[YXLoginStatusTool sharedLoginStatus] getTokenId];
    [manager.requestSerializer setValue:token forHTTPHeaderField:@"id"];

//请求地址    
    NSString *URLSTR = @"";
    
    [manager POST:URLSTR parameters:nil constructingBodyWithBlock:^(id  _Nonnull formData) {

      //转成data

      self.justimagedata = UIImagePNGRepresentation(pickerImagePic);

//按照表单格式把二进制文件写入formData表单
        [formData appendPartWithFileData:self.justimagedata name:@"" fileName:@"" mimeType:@"image/png"];
    
        [formData appendPartWithFileData:self.backimagedata name:@"" fileName:@"" mimeType:@"image/png"];
        
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        YXLog(@"++++%@+++",uploadProgress);
        
    }  success:^(NSURLSessionDataTask *task, id responseObject) {
    
          YXLog(@"responseObject == %@--++--%@----", [self getResponseObjcWithTask:responseObject],[self getRespodHeaderWithTask:task]);
        
        if ([[self getRespodHeaderWithTask:task][@"Status"] isEqualToString:@"1"]) {
           
            //成功
        }else{
            
            [YXAlearMnager ShowAlearViewWith:[self getRespodHeaderWithTask:responseObject][@"errorMsg"] Type:2];
        }
        [YXNetworkHUD dismiss];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        [YXNetworkHUD dismiss];
        
         YXLog(@"发送失败+++++%@++++%@",error,[self getRespodHeaderWithTask:task]);
        
        [YXAlearMnager ShowAlearViewWith:@"头像更换失败" Type:2];
    }];
//** 获取响应头 */
- (id)getRespodHeaderWithTask:(NSURLSessionTask *)task
{
    NSHTTPURLResponse *respond = (NSHTTPURLResponse *)task.response;
    return respond.allHeaderFields;
}
-(id)getResponseObjcWithTask:(id )responseObect{
    id json;
    NSError *error;
    json = [NSJSONSerialization JSONObjectWithData:responseObect options:0 error:&error];
    if (error) {
        json = [[NSString alloc] initWithData:responseObect encoding:NSUTF8StringEncoding];
    }
    return json;
}

 

转载于:https://www.cnblogs.com/liuwenqiang/p/6426277.html

你可能感兴趣的:(iOS 提交form表单,上传图片)