Objective-C如何使用AFNetwork上传字符串

时间:2015-09-03 03:27:52

标签: php ios objective-c iphone afnetworking

我使用AFNetwork上传照片和字符串(我将uitextview转换为字符串)到我的服务器并保存在数据库中但我不知道使用AFNetwork上传字符串但是我用它来上传我的照片它的工作原理是我用于viewcontroller的php代码

<?php
include(“connect.php");
$uploaddir = "post_comment/original/";      //Uploading to same directory as PHP file
$file = basename($_FILES['userfile']['name']);
$uploadFile = $file;
$randomNumber = rand(0, 99999);
$newName = $uploaddir . $randomNumber . $uploadFile;
$comment_text = nl2br($_POST['comment']);
$post_no = $_POST['post_no'];
$mem_slug = $_POST['id'];
$timest = date("Y-m-d H:i:s");
echo  "it is: ".$file;


if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
    echo "Temp file uploaded. \r\n";
} else {
    echo "Temp file not uploaded. \r\n";
}

if ($_FILES['userfile']['size']> 3000000) {
    exit("Your file is too large.");
}


if(copy($_FILES['userfile']['tmp_name'],$newName)){
    $sql3 = $conn->prepare("INSERT INTO `post_comment`(`comment_id`,`post_id`,`member_id`,`comment`,`image`,`status`,`timestp`) VALUES('',:postid,:member,:comment,:image,'1',:timestp)");
    $sql3 ->bindValue(':postid',$post_no);
    $sql3 ->bindValue(':member',$mem_slug);
    $sql3 ->bindValue(':comment',$comment_text);
    $sql3 ->bindValue(':image',$newName);
    $sql3 ->bindValue(':timestp',$timest);
    $sql3 ->execute();
}
    echo "upload finished";
?>

Viewcontroller.m

NSString *comment = _commentText.text;
NSDictionary *data= @{@"post_id":urlpost,@"member_id":member_id,@"comment":self.commentText.text};
    [manager POST:@"http://www.mysiteurl.com/member/comment_upload2.php"
       parameters:data constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
     {
         [formData appendPartWithFileData:UIImageJPEGRepresentation(self.image, 100) name:@"userfile" fileName:@"img.jpg" mimeType:@"image/jpg"];
     }
          success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSString* str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
         NSLog(@"response is :  %@",str);
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"Error: %@ *****", error);
     }];
}

2 个答案:

答案 0 :(得分:0)

使用AFNetwork上传图片和字符串。

试试这段代码

AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://www.mysiteurl.com"]];
NSData *imageData = UIImageJPEGRepresentation(yourimage.image, 0.5);
NSDictionary *parameters= @{@"post_id":urlpost,@"member_id":member_id,@"comment":self.commentText.text};
AFHTTPRequestOperation *op = [manager POST:@"/member/comment_upload2.php" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    //do not put image inside parameters dictionary as I did, but append it!
    [formData appendPartWithFileData:imageData name:@"file" fileName:[NSString stringWithFormat:@"photo_%f.jpg",[NSDate timeIntervalSinceReferenceDate]] mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);

    [[NSNotificationCenter defaultCenter] postNotificationName:@"PostAdded" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@ ***** %@", operation.responseString, error);
}];
[op start];

答案 1 :(得分:0)

您可以使用以下代码上传评论字符串..

NSString *comment = _commentText.text;
NSDictionary *data= @{@"post_id":urlpost,@"member_id":member_id,@"comment":self.commentText.text};

NSString *urlString=@"http://www.mysiteurl.com/member/comment_upload2.php”;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json",@"text/html", nil];
    manager.requestSerializer=[AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
    //manager.responseSerializer=[AFJSONResponseSerializer serializer];
    NSString *stringCleanPath = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [manager POST:stringCleanPath parameters:maindict success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSDictionary *jsondict =responseObject;
         NSLog(@"jsondict>>>%@",jsondict);         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"error is %@",error);
         [delegate failedResponseWithAnyType:[error localizedDescription] withServiceType:serviceTypeString];
     }];

//或者您可以尝试使用以下代码上传字符串和照片

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json",@"text/html", nil];
        manager.requestSerializer=[AFJSONRequestSerializer serializer];
        manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
        //manager.responseSerializer=[AFJSONResponseSerializer serializer];
        NSString *stringCleanPath = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *comment = _commentText.text;
NSDictionary *data= @{@"post_id":urlpost,@"member_id":member_id,@"comment":self.commentText.text};
    [manager POST:stringCleanPath
       parameters:data constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
     {
         [formData appendPartWithFileData:UIImageJPEGRepresentation(self.image, 100) name:@"userfile" fileName:@"img.jpg" mimeType:@"image/jpg"];
     }
          success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSString* str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
         NSLog(@"response is :  %@",str);
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"Error: %@ *****", error);
     }];
}

检查AFURLResponseSerialization.m

- (instancetype)init方法

self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];

它不会因为acceptedContentTypes是NSSet而来。你只通过NSSet ......!检查一下。

希望它可以帮助你.......!