iOS 提交form表单,上传图片

Posted 佛系码农

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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<AFMultipartFormData>  _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;
}

 

以上是关于iOS 提交form表单,上传图片的主要内容,如果未能解决你的问题,请参考以下文章

摒弃FORM表单上传图片,异步批量上传照片

jquery mobile 表单提交 图片/文件 上传

jquery.form.js ajax提交上传文件

python实现本地图片上传到服务区

form表单提交图片禁止跳转

怎么用ajax 提交上传的文件上传后在界面显示出来。但界面不刷新