AFN传文件和参数

来源:互联网 发布:java中文相似度匹配 编辑:程序博客网 时间:2024/06/07 01:11

使用AFNetWorking传文件和参数:

#pragma mark -上传问题图片

- (void)uploadQuestionImage:(UIImage*)questionImage withQuestionID:(NSString*)questionID
{
   
AppDelegate * app = [UIApplicationsharedApplication].delegate;
   
   
NSData *imageData =UIImageJPEGRepresentation(self.questionImage,1.0);
   
   
NSMutableDictionary * parameters = [NSMutableDictionarydictionary];
   
    [parameters
setObject:questionIDforKey:@"exID"];
   
   
NSMutableURLRequest *request = [[AFHTTPClientclientWithBaseURL:[NSURLURLWithString:dUrl_serverAddress]]multipartFormRequestWithMethod:@"POST"path:@"Path/UploadTitleImage/"parameters:parametersconstructingBodyWithBlock: ^(id<AFMultipartFormData>formData) {
       
        [formData
appendPartWithFileData:imageDataname:@"image"fileName:@"quePic.jpg"mimeType:@"image/jpeg"]; //图片
    }];

   
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperationalloc]initWithRequest:request];
   
    [operation
setUploadProgressBlock:^(NSUIntegerbytesWritten, long long totalBytesWritten,longlongtotalBytesExpectedToWrite) {
       
float progress = totalBytesWritten / (float)totalBytesExpectedToWrite;
       
NSLog(@"Sent Pic %f ..",progress);
       
    }];
   
   
    [operation
start];
    [operation
setCompletionBlockWithSuccess:^(AFHTTPRequestOperation*operation, id responseObject) {
       
       
NSLog(@" QuestionPictureUploadDidFinish:  %@ ",[operationresponseString]);
       
NSString * response =[operationresponseString];
       
       
NSError *error = nil;
       
NSData *fileIdData = [responsedataUsingEncoding:NSUTF8StringEncoding];
       
NSDictionary *dicRoot = [NSJSONSerializationJSONObjectWithData:fileIdDataoptions:NSJSONReadingMutableLeaveserror:&error];
       
NSDictionary *dictfil = [dicRootobjectForKey:@"json"];
       
       
       
int state = [[dictfilvalueForKey:@"state"]intValue];
       
//上传成功
       
if (state==1)
        {
           
NSString *msg = [NSStringstringWithFormat:@"%@", [dictfil objectForKey:@"msg"]];
            [app
showMsg:msg];
        }
       
//上传失败
       
else
        {
           
NSString *msg = [NSStringstringWithFormat:@"%@", [dictfil objectForKey:@"msg"]];
            [app
showMsg:msg];
        }
       
    }
failure:^(AFHTTPRequestOperation*operation, NSError *error) {
       
NSLog(@"上传失败error: %@",  operation.responseString);
        [app
showMsg:@"上传失败"];
       
    }];

}
0 0
原创粉丝点击