通过imagepicker将图像上传到服务器不起作用(需要解决方案)

时间:2012-02-19 16:41:05

标签: php ios xcode uiimage uiimagepickercontroller

作为这个问题的后续问题Uploading images to server doesn't work(在那里你可以找到我的php文件)我意识到它为什么不起作用。但我不知道解决方案。正如您在代码中看到的那样(几行向下)我将我的图像提供给php文件,但它不会将其识别为图像。所以我希望有人可以帮助它,并且知道(可能是显而易见的)解决方案:

 - (IBAction)changepic:(id)sender{

    picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentModalViewController:picker animated:YES];
    }

 - (void)imagePickerController:(UIImagePickerController *) Picker didFinishPickingMediaWithInfo:(NSDictionary *)info{

double compressionRatio=1;
NSData *imageData=UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage],compressionRatio);
while ([imageData length]>50000) { 
    compressionRatio=compressionRatio*0.50;
    imageData=UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage],compressionRatio);
}

UIImage *yourUIImage;
yourUIImage = [info objectForKey:UIImagePickerControllerOriginalImage];
imageData = [NSKeyedArchiver archivedDataWithRootObject:yourUIImage];
[[NSUserDefaults standardUserDefaults] setObject:imageData forKey:@"bild"];
[[NSUserDefaults standardUserDefaults] synchronize];



NSData *imageData2 = UIImageJPEGRepresentation(yourUIImage, 90);
NSString *urlString = @"http://myserver/upload.php";


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];

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

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"imagename.jpg\"\r\n",index] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData2]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

NSLog(@"%@", returnString);

[self dismissModalViewControllerAnimated:YES];
}

2 个答案:

答案 0 :(得分:4)

我把它变成了一个简单的函数,可以包含在所有项目中使用。在我的例子中,远程服务器是一个PHP脚本。

这就是函数的使用方式:

// form text fields and values
NSArray *formfields = [NSArray arrayWithObjects:@"name", @"date", @"purpose", @"comment", nil];
NSArray *formvalues = [NSArray arrayWithObjects:@"Write Blog", @"31-03-2011", @"For Test", @"Just Comment", nil];
NSDictionary *textParams = [NSDictionary dictionaryWithObjects:formvalues forKeys:formfields];

// if, there are any images in the form
NSArray *images = [NSArray arrayWithObjects:@"myimage1.png", @"myimage2.png", nil];

// submit the form
[self doPostWithText:textParams andImage:images];

这是doPostWithText:andImage:

的函数定义
- (void) doPostWithText:(NSDictionary *)textParams andImage:(NSArray *)imageParams
{
    NSString *urlString = @"http://mysite.com/myscript.php";
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];

    NSMutableData *body = [NSMutableData data];

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

    // add the image form fields
    for (int i=0; i<[imageParams count]; i++) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: attachment; name=\"image%d\"; filename=\"%@\"\r\n", i, [imageParams objectAtIndex:i]] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[NSData dataWithData:UIImageJPEGRepresentation([UIImage imageNamed:[imageParams objectAtIndex:i]], 90)]];
        [body appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

    }

    // add the text form fields
    for (id key in textParams) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithString:[textParams objectForKey:key]] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }

    // close the form
    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    // set request body
    [request setHTTPBody:body];

    // send the request (submit the form) and get the response
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

    NSLog(@"%@", returnString);
}

在PHP方面,我将得到如下数据:

$_POST

Array
(
    [name] => Write Blog
    [purpose] => For Test
    [comment] => Just Comment
    [date] => 31-03-2011
)

$_FILES


Array
(
    [image0] => Array
        (
            [name] => myimage1.png
            [type] => application/octet-stream
            [tmp_name] => /junk/temp/phpsKiVxx
            [error] => 0
            [size] => 23602
        )

    [image1] => Array
        (
            [name] => myimage2.png
            [type] => application/octet-stream
            [tmp_name] => /junk/temp/phpNVGDoB
            [error] => 0
            [size] => 4620
        )

)

答案 1 :(得分:1)

删除这些行并尝试...这将有效...

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