【问题标题】:Upload image along with other data in same POST在同一个 POST 中上传图像和其他数据
【发布时间】:2011-02-21 12:35:12
【问题描述】:

我想使用 POST 方法上传图片。我可以单独上传图片。但我想将它们与我需要发送的其他数据一起发布到服务器。谁能帮帮我。知道如何发帖

这是我发送数据的代码。除了这个,我还需要把图片和这个一起发送

postString = [NSString stringWithFormat:@"u=TuNmae&p=pass&o=onr&j=123&a=321&d=8765&t=123&at=need&image="];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url1];
    NSString *msgLength = [NSString stringWithFormat:@"%d", [postString length]];

    [req addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [req addValue:msgLength forHTTPHeaderField:@"Content-Length"];
    [req setHTTPMethod:@"POST"];
    [req setHTTPBody: [postString dataUsingEncoding:NSUTF8StringEncoding]];

    NSData *returnData = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];

    webData = [[NSMutableData data] retain];
    [webData appendData:returnData];
    NSLog(@"attempt%@",webData);
    NSString *webResult;
    webResult = [[NSString alloc] initWithData:webData encoding:NSASCIIStringEncoding];

    webResult = [webResult stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    NSLog(@"str %@",webResult);

我需要将图像插入到 postString 中。最后一个参数。

【问题讨论】:

  • 您能提供更多信息吗?你说的是原生应用吗? UIWebView/Web-app?
  • 不,我没有使用 uiwebView。我有一些细节(字符串),我也需要发送图像。请帮忙
  • @rakendu 我也有同样的问题,如果你解决了请告诉我

标签: iphone image post


【解决方案1】:

您必须将 enctype 表单属性设置为“multipart/form-data”

form enctype="multipart/form-data"

然后你可以上传文件输入和其他文本隐藏输入在同一个 表单和相同的提交。

在您的 api 中执行此操作

NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; [request addValue:contentType forHTTPHeaderField: @"Content-Type"]; //file data NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:@"ImageFile.png"]; NSData *imageData = [[NSData alloc] initWithContentsOfFile:fullPathToFile];

【讨论】:

  • 我想知道这是否适用于 iPhone。因为我没有在任何地方使用标签
【解决方案2】:

Rakendu 尝试以下方式,您可以通过这个发送...

NSString *url = @"www.google.com";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];

[request setHTTPMethod: @"POST"];

NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BOUNDARY];  
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];  

NSMutableData *body = [NSMutableData data];

[self addToDataField:body field:@"firstname" value:txtFirstName.text];
if (updatedImage == TRUE)
        {

    [body appendData:[[NSString stringWithFormat:@"\r\n\r\n--%@\r\n",BOUNDARY] dataUsingEncoding:NSUTF8StringEncoding]];  
    [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"file\"; filename=\"image.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];  
    [body appendData:[[NSString stringWithString:@"Content-Type: image/png\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];  
    [body appendData:UIImagePNGRepresentation(image)];  
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",BOUNDARY] dataUsingEncoding:NSUTF8StringEncoding]];  

    updatedImage = FALSE;
    }
    NSLog(@"%@",body);

NSString *temp =  [NSString stringWithFormat:@"%i", [body length]];
[request setHTTPBody:body];
[request setHTTPMethod: @"POST"];
[request addValue:temp forHTTPHeaderField:@"Content-Length"];

NSLog(@"%@",request);

NSError *error = nil;
NSURLResponse *response;
urlData = [[[NSMutableData data] retain] autorelease];
urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

希望这篇文章对你有所帮助..

【讨论】:

    【解决方案3】:

    我还想在同一个 POST 中上传一张图片和其他数据,关于上传图片的大部分信息只是在一个服务器连接中单独上传一张图片,这就是我解决这个问题的方法。

    这是PHP

    <?php
    /* As you can see there are more values not only the image */
    $variableOne    = $_POST['variableOne'];
    $variableTwo    = $_POST['variableTwo'];
    $variableThree  = $_POST['variableThree'];
    $variableFour   = $_POST['variableFour'];
    $variableFive   = $_POST['variableFive'];
    $variableSix    = $_POST['variableSix'];
    $variableSeven  = $_POST['variableSeven'];
    $variableEight  = $_POST['variableEight'];
    $variableNine   = $_POST['variableNine'];
    $variableTen    = $_POST['variableTen'];
    
    /* Our image */
    $image = $_REQUEST['image'];
    
    /* This is for trying to get a unique name for the image file, since maybe you want to store large amount of images */
    $currentDate = date("Y-m-d");
    $name  = "" . $currentDate . microtime() . rand(0, 999) . rand(0, 999) . rand(0, 999) . ".jpg";
    
    /* 
     * Here comes the image stuff
     */
    if (file_exists($name)) {
        echo "File already exists";
    } else {
            /* Decoding image */
            $binary = base64_decode($image);
    
            /* Opening image */
            $file = fopen($name, 'wb');
    
            /* Writing to server */
            fwrite($file, $binary);
    
            /* Closing image file */
            fclose($file);
    
            echo "Added";
        }   
    }   
    ?>
    

    然后在Xcode中复制粘贴这个方法(取自Creating a base-64 string from NSData

    - (NSString*)base64forData:(NSData*) theData {
        const uint8_t* input = (const uint8_t*)[theData bytes];
        NSInteger length = [theData length];
    
        static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    
        NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
        uint8_t* output = (uint8_t*)data.mutableBytes;
    
        NSInteger i;
        for (i=0; i < length; i += 3) {
            NSInteger value = 0;
            NSInteger j;
            for (j = i; j < (i + 3); j++) {
                value <<= 8;
    
                if (j < length) {
                    value |= (0xFF & input[j]);
                }
            }
    
            NSInteger theIndex = (i / 3) * 4;
            output[theIndex + 0] =                    table[(value >> 18) & 0x3F];
            output[theIndex + 1] =                    table[(value >> 12) & 0x3F];
            output[theIndex + 2] = (i + 1) < length ? table[(value >> 6)  & 0x3F] : '=';
            output[theIndex + 3] = (i + 2) < length ? table[(value >> 0)  & 0x3F] : '=';
        }
    
        return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    }
    

    在 YourViewController.h 文件中

    @interface YourViewController : UIViewController {
        NSURLConnection *serverConnection;
        NSMutableData *returnData;
    }
    

    这是服务器连接代码

    NSURL *sendURL = [NSURL URLWithString:@"http://yourdomainname/imagefolder/phpscript.php"];
    
    NSMutableURLRequest *sendRequest = [NSMutableURLRequest requestWithURL:sendURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
    
    [sendRequest setHTTPMethod:@"POST"];
    
    [sendRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    NSData *imageData = UIImageJPEGRepresentation(yourImage, 1.0);
    
    NSString *encodedString = [[self base64forData:imageData] stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
    
    NSString *dataToSend = [[NSString alloc] initWithFormat:@"variableOne=%@&variableTwo=%@&variableThree=%@&variableFour=%@&variableFive=%@&variableSix=%@&variableSeven=%@&variableEight=%@&variableNine=%@&variableTen=%@&image=%@", valueOne, valueTwo, valueThree, valueFour, valueFive, valueSix, valueSeven, valueEight, valueNine, valueTen, encodedString];
    
    [sendRequest setHTTPBody:[dataToSend dataUsingEncoding:NSUTF8StringEncoding]];
    
    serverConnection = [[NSURLConnection alloc] initWithRequest:sendRequest delegate:self];
    
    [serverConnection start];
    

    设置服务器连接的委托方法

    - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
        returnData = [[NSMutableData alloc] init];
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
        [returnData appendData:data];
    }
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        if (connection == serverConnection) {
            NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    
            NSLog(@"Response: %@", responseString);
    
            if ([responseString isEqualToString:@"Added"]) {
    
                /* Make something on success */
    
            } else {
    
                /* Make something else if not completed with success */
    
            }
        }
    }
    
    - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
        /* Make something on failure */
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-31
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      • 1970-01-01
      • 2019-08-24
      • 1970-01-01
      • 2020-11-17
      相关资源
      最近更新 更多