在同一POST中上传图像以及其他数据

时间:2011-02-21 12:35:13

标签: iphone image post

我想使用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中。最后一个参数。

3 个答案:

答案 0 :(得分: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];

答案 1 :(得分:0)

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

希望这个对你有帮助..

答案 2 :(得分:0)

我还想在同一个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 */
}