文中的 XXXXXXXXXX根据你自己的参数填写
- (void)uploadImageWithImage:(NSString *)imagePath
{
//上传其他所需参数
NSString *userId=XXXXXXXXXXX;
NSString *token=XXXXXXXXXXX;
//上传请求POST
AFHTTPClient *client=[AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@""]];
NSString *urlString=[NSString stringWithFormat:@"上传服务器地址];
NSDictionary *dic=[[NSDictionary alloc] initWithObjectsAndKeys:userId,@"XXXXXX",token,@"XXXXXX", nil];
NSURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:urlString parameters:dic constructingBodyWithBlock:^(id formData) {
//得到需要上传的数据
NSData *data=[NSData dataWithContentsOfFile:imagePath];
//上传时使用当前的系统事件作为文件名
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
//服务器上传文件的字段和类型
[formData appendPartWithFileData:data name:@"XXXXX" fileName:fileName mimeType:@"image/jpg/file"];
}];
// 3. operation包装的urlconnetion
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"上传完成");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"上传失败->%@", error);
}];
//执行
[client.operationQueue addOperation:op];
}