【问题标题】:Retrieve HTTP POST variables using multipart/form-data sent from an iOS device使用从 iOS 设备发送的 multipart/form-data 检索 HTTP POST 变量
【发布时间】:2013-04-11 19:05:37
【问题描述】:

我需要检索从我的 iOS 应用程序发送的 POST 变量,但到目前为止我没有运气。这是一些背景:

我有一个 iOS 应用程序,它将图像和一些变量一起发布到 php 页面,该页面只是将变量保存在文件中(用于调试)并将图像移动到当前目录(服务器端)。我可以使用 $_FILE 变量毫无问题地处理图像,但是我似乎根本无法获得任何 POST 参数。

一些一般信息和我尝试过的:

  • 尝试使用 $_POST 获取 post 变量,然后转储 $_POST...它是空的
  • 尝试转储 $HTTP_RAW_POST_DATA(尽管 this page 表示使用 multipart/form-data 时未填充)
  • 在看到this post 后检查了“post_max_size”变量(它是 8MB,我在 KB 范围内发送)
  • 使用wireshark 验证服务器确实接收到变量

我正在使用修改后的示例代码from here

// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];

NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:@"1.0" forKey:@"ver"];
[_params setObject:@"en" forKey:@"lan"];
[_params setObject:[NSString stringWithFormat:@"%@", @"myUserName"] forKey:@"userId"];

// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = @"V2ymHFg03ehbqgZCaKO6jy";

// string constant for the post parameter 'file'
NSString *FileParamConstant = @"media";

//Setup request URL
NSURL *requestURL = [[NSURL alloc] initWithString:@"http://myWebAddress/myAction.php"];

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

// add params (all params are strings)
for (NSString *param in _params) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}

// add image data
NSData *imageData = UIImageJPEGRepresentation([self.imageButtonOutlet backgroundImageForState:UIControlStateNormal], 1.0);
if (imageData) {
    printf("appending image data\n");
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\'%@\'; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

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

// setting the body of the post to the reqeust
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

// set URL
[request setURL:requestURL];

NSURLConnection *postConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[postConnection start];
[postConnection release];

另外,这里是 myAction.php,就像现在一样:

<?php

$fp_file = fopen("./output_files.txt", "w");
$fp_post = fopen("./output_post.txt", "w");

$post_content = var_export($_POST , TRUE);
$file_content = var_export($_FILES, TRUE);
fwrite($fp_file, $file_content);
fwrite($fp_post, $post_content);


fclose($fp_file);
fclose($fp_post);

move_uploaded_file( $_FILES['media']['tmp_name'], "test.jpg");

?>

【问题讨论】:

    标签: php ios objective-c http-post


    【解决方案1】:

    经过 4 小时的调试,问题出在我的 php 代码中……已被编辑以反映更改。变量 $post_content 是用名称 $post_contnet 创建的。希望这至少可以作为其他尝试实施类似服务的代码指南。

    你不能解决愚蠢的问题。

    【讨论】:

      【解决方案2】:

      自己实现HTTP协议有什么原因吗?

      那里有几个网络包

      https://github.com/AFNetworking/AFNetworking

      我相信支持多部分表单数据。

      【讨论】:

        【解决方案3】:

        使用以下代码上传我只在此函数的最后一行进行了更改,您可以根据您的要求为NSURLConnection设置代表。

        -(void)upload
        {
            // create request
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
            [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
            [request setHTTPShouldHandleCookies:NO];
            [request setTimeoutInterval:30];
            [request setHTTPMethod:@"POST"];
        
            NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
            [_params setObject:@"1.0" forKey:@"ver"];
            [_params setObject:@"en" forKey:@"lan"];
            [_params setObject:[NSString stringWithFormat:@"%@", @"myUserName"] forKey:@"userId"];
        
            // the boundary string : a random string, that will not repeat in post data, to separate post data fields.
            NSString *BoundaryConstant = @"V2ymHFg03ehbqgZCaKO6jy";
        
            // string constant for the post parameter 'file'
            NSString *FileParamConstant = @"media";
        
            //Setup request URL
            NSURL *requestURL = [[NSURL alloc] initWithString:@"http://myWebAddress/myAction.php"];
        
            // set Content-Type in HTTP header
            NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];
            [request setValue:contentType forHTTPHeaderField: @"Content-Type"];
        
            // post body
            NSMutableData *body = [NSMutableData data];
        
            // add params (all params are strings)
            for (NSString *param in _params) {
                [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
                [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
                [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
            }
        
            // add image data
            NSData *imageData = UIImageJPEGRepresentation([self.imageButtonOutlet backgroundImageForState:UIControlStateNormal], 1.0);
            if (imageData) {
                printf("appending image data\n");
                [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
                [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\'%@\'; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
                [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
                [body appendData:imageData];
                [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
            }
        
            [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
        
            // setting the body of the post to the reqeust
            [request setHTTPBody:body];
        
            // set the content-length
            NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        
            // set URL
            [request setURL:requestURL];
        
            NSURLResponse *response = nil;
            NSError *err = nil;
            NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
            NSString *str = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
            NSLog(@"Response : %@",str);
        }
        

        并在myAction.php 文件中写入PHP 代码以读取您的参数

        <?php
            echo "FileType :". $_FILES["media"]["type"] ;
            echo "FileName :". $_FILES["media"]["name"] ;
            echo "FileSize :".($_FILES["media"]["size"] / 1024)/100 ;
            echo "Version :".$_REQUEST["ver"];
            echo "Language :".$_REQUEST["lan"];
        ?>
        

        【讨论】:

          猜你喜欢
          • 2014-05-13
          • 1970-01-01
          • 1970-01-01
          • 2016-09-08
          • 1970-01-01
          • 1970-01-01
          • 2013-04-09
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多