繁体   English   中英

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

[英]Send string and image, audio, video to the server in one request on iOS/Objective-C

我想发送信息以及多媒体文件(如果找到)。 所有都保存在NSString和NSData中,只有一个HTTP请求。 信息和多媒体文件未成功附加到正文中。 我可以成功发送信息,但我无法在单个HTTP请求中发送多媒体文件。

iOS文件

//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:@"-%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [postBody appendData:[@"Content-Disposition: form-data; name=\"value1\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

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

    [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    // "value2" part

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

    [postBody appendData:[@"Content-Disposition: form-data; name=\"value2\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

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

    [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    // "value3" part

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

    [postBody appendData:[@"Content-Disposition: form-data; name=\"value3\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

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

    [postBody appendData:[@"\r\n" 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:@"-%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];

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

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

    [postBody appendData:[@"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

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

    // Add it to the body

    [postBody appendData:image];

    [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    // Final boundary

    [postBody appendData:[[NSString stringWithFormat:@"-%@-\r\n", 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文件

//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!\n";

                $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!\n", "image Not Uploaded!\n");
                        }
                    }
                    catch (Exception $ex) {
                        echo "Image Not Uploaded!\n";
                    }
                }

                // 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!\n", "Audio Not Uploaded!\n");
                        }
                    }
                    catch (Exception $ex) {
                        echo "Audio Not Uploaded!\n";
                    }
                }

                // 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!\n", "Video Not Uploaded!\n");
                        }
                    }
                    catch (Exception $ex) {
                        echo "Video Not Uploaded exception!\n";
                    }
                }
            }
        }
        else {
            echo "Sending Failure!";
        }
    }
    else {
        echo 'Invalid Request';
    }
?>

我使用AFNetworking,这是有效的

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];

希望这会奏效

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM