dras2334 2015-02-26 19:16
浏览 68

在iOS / Objective-C上的一个请求中将字符串和图像,音频,视频发送到服务器

I want to send information as well as multimedia files (if found). All are saved in both NSString and NSData, with a single HTTP request. Information and multimedia files are not appended successfully in the body. I can send the information successfully, but I can't send the multimedia files with it in a single HTTP request.

iOS file

//My iOS code
-(void)uploadToServer {

    NSDate *date = [[NSDate alloc] init];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-YYYY HH:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:date];


    NSURL *postURL = [NSURL URLWithString:@"my php file"];

    // Create the connection

    NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:postURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

    NSMutableURLRequest *postRequest = [[NSMutableURLRequest alloc] init];
    [postRequest setURL:postURL];

    // Set POST or GET HTTP request method
    [postRequest setHTTPMethod:@"POST"];

    NSString *stringBoundary = @"ghkyreñnhjfhdj-74f5f-gfg5-gggff";

    // Header value
    NSString *headerBoundary = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", stringBoundary];

    // Set header
    [postRequest addValue:headerBoundary forHTTPHeaderField:@"Content-Type"];

    // Create data
    NSMutableData *postBody = [NSMutableData data];

    // "value1" part
    [postBody appendData:[[NSString stringWithFormat:@"-%@
", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [postBody appendData:[@"Content-Disposition: form-data; name=\"value1\"

" dataUsingEncoding:NSUTF8StringEncoding]];

    [postBody appendData:[@"value1" dataUsingEncoding:NSUTF8StringEncoding]];

    [postBody appendData:[@"
" dataUsingEncoding:NSUTF8StringEncoding]];

    // "value2" part

    [postBody appendData:[[NSString stringWithFormat:@"-%@
", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [postBody appendData:[@"Content-Disposition: form-data; name=\"value2\"

" dataUsingEncoding:NSUTF8StringEncoding]];

    [postBody appendData:[@"value2" dataUsingEncoding:NSUTF8StringEncoding]];

    [postBody appendData:[@"
" dataUsingEncoding:NSUTF8StringEncoding]];

    // "value3" part

    [postBody appendData:[[NSString stringWithFormat:@"-%@
", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [postBody appendData:[@"Content-Disposition: form-data; name=\"value3\"

" dataUsingEncoding:NSUTF8StringEncoding]];

    [postBody appendData:[@"value3" dataUsingEncoding:NSUTF8StringEncoding]];

    [postBody appendData:[@"
" dataUsingEncoding:NSUTF8StringEncoding]];


    // Add more data here

    // Add image from picker view and convert UIImage to NSData

    //NSData *imageData = UIImageJPEGRepresentation(image.image, 90);

    [postBody appendData:[[NSString stringWithFormat:@"-%@
", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"%@.jpg\"
", dateString]dataUsingEncoding:NSUTF8StringEncoding]];

    [postBody appendData:[@"Content-Type: image/jpeg
" dataUsingEncoding:NSUTF8StringEncoding]];

    [postBody appendData:[@"Content-Transfer-Encoding: binary

" dataUsingEncoding:NSUTF8StringEncoding]];

    [postBody appendData:[NSData dataWithData:image]];

    // Add it to the body

    [postBody appendData:image];

    [postBody appendData:[@"
" dataUsingEncoding:NSUTF8StringEncoding]];

    // Final boundary

    [postBody appendData:[[NSString stringWithFormat:@"-%@-
", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];

    // Add the body to post

    [postRequest setHTTPBody:postBody];


    [request setTimeoutInterval:30];

    NSURLResponse * response = nil;
    NSError * error = nil;
    NSData * rcvdata = [NSURLConnection sendSynchronousRequest:request
                                          returningResponse:&response
                                                      error:&error];

    if (rcvdata != nil)
    {
        NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success" message:returnString delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];

        NSLog(@"Return String= %@", returnString);
    }
    else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failed" message:@"Check your internet connection" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
    }

}

PHP file

//My PHP file is like this:
<?php

        // Check for proper request
        if (isset($_POST['value1'])) {
            $value1 = $_POST['value1'];
            $value2 = $_POST['value2'];
            $value3 = $_POST['value3'];

            // Insert data into the info table

            $query = "INSERT INTO `info` (`value1`, `value2`, `value3) VALUES ('$value1', '$value2', '$value3')";
            $result = mysql_query($query);
            if ($result) {
                echo "Successfully sent your data!
";

                $target_path = "multimedia/";

                // Check for image
                $prefix="X".  time();
                if (isset($_FILES['image']['name'])) {
                    $target_path1 = $target_path . basename($prefix.$_FILES['image']['name']);
                    try {
                        if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path1)) {
                            throw new Exception('Could not move file');
                        }
                        else {
                           insertMultimedia($value1, 3, $prefix.$_FILES['image']['name'], "Image Uploaded!
", "image Not Uploaded!
");
                        }
                    }
                    catch (Exception $ex) {
                        echo "Image Not Uploaded!
";
                    }
                }

                // Check for audio
                if (isset($_FILES['audio']['name'])) {
                    $target_path2 = $target_path . basename($prefix.$_FILES['audio']['name']);
                    try {
                        if (!move_uploaded_file($_FILES['audio']['tmp_name'], $target_path2)) {
                            throw new Exception('Could not move file');
                        }
                        else {
                            insertMultimedia($value1, 2, $prefix.$_FILES['audio']['name'], "Audio Uploaded!
", "Audio Not Uploaded!
");
                        }
                    }
                    catch (Exception $ex) {
                        echo "Audio Not Uploaded!
";
                    }
                }

                // Check for video
                if (isset($_FILES['video']['name'])) {
                    $target_path3 = $target_path . basename($prefix.$_FILES['video']['name']);
                    try {
                        if (!move_uploaded_file($_FILES['video']['tmp_name'], $target_path3)) {
                            throw new Exception('Could not move file');
                        }
                        else {
                            insertMultimedia($value1, 1, $prefix.$_FILES['video']['name'], "Video Uploaded!
", "Video Not Uploaded!
");
                        }
                    }
                    catch (Exception $ex) {
                        echo "Video Not Uploaded exception!
";
                    }
                }
            }
        }
        else {
            echo "Sending Failure!";
        }
    }
    else {
        echo 'Invalid Request';
    }
?>
  • 写回答

1条回答 默认 最新

  • doubi1624 2015-03-03 03:48
    关注

    i use AFNetworking and this is working

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    NSDictionary *parameters = @{@"value1": @"value1",
                                 @"value2": @"value2",
                                 @"value3": @"value1",
                                 };
    // BASIC AUTH (if you need):
    manager.securityPolicy.allowInvalidCertificates = YES;
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"foo" password:@"bar"];
    // BASIC AUTH END
    
    NSString *URLString = @"php file";
    
    /// !!! only jpg, have to cover png as well
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    
    
        if (image) {
            [formData appendPartWithFileData:image name:@"image" fileName:[NSString stringWithFormat:@"%@.jpg",dateString] mimeType:@"image/jpeg"];
            NSLog(@"image: %@",image);
        }
    
        if (video) {
            [formData appendPartWithFileData:video name:@"video" fileName:[NSString stringWithFormat:@"%@.mp4",dateString] mimeType:@"video/quicktime"];
            NSLog(@"video: %@",video);
        }
    
        if (audio) {
            [formData appendPartWithFileData:audio name:@"audio" fileName:[NSString stringWithFormat:@"%@.mp3",dateString] mimeType:@"audio/m4a"];
            NSLog(@"audio: %@",audio);
        }
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Success %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Failure" message:@"Sending Failure" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        NSLog(@"Failure %@, %@", error, operation.responseString);
    }];
    
    [self dismissViewControllerAnimated:NO completion:nil];
    

    hope this will work

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。