从iOS设备上传图像到php服务器问题?(500内部服务器错误)

时间:2016-08-09 11:21:51

标签: php ios

MainActivity

iOS开发人员可以尝试将图像发送到PHP服务器。但他们得到的错误如上所述

我该如何解决这个问题?

是在iOS代码问题还是PHP方面?

通过邮递员检查: enter image description here

通过使用此网址,他们向我发送了多张图片,但如果是单张图片,则表示工作正常,但尝试发送多张图片却无效:https://charangiri.wordpress.com/2014/09/22/how-to-upload-multiple-image-to-server/

1 个答案:

答案 0 :(得分:1)

您可以使用以下此功能将多个图像上传到服务器。我用过的imagesarray变量是存储UIImage对象。您可以根据需要进行更改。

- (void)uploadImagesToServer{
//create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

//Set Params
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:@"POST"];

//Create boundary, it can be anything
NSString *boundary = @"------friendlyWagonBoundary4QuqLuM1cE5lMwCy";

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

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

for (int i=0; i<[imagesArray count]; i++)
{
    UIImage *images=[imagesArray objectAtIndex:i];
    NSData* imageData = UIImageJPEGRepresentation(images, 0.7);

    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image%d\"; filename=\"image%d\"\r\n", i+1,i+1] 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]];

}
//Close off the request with the boundary
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

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

// set URL
[request setURL:[NSURL URLWithString:@"http://example.com"]]; // Give your URL here.

[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

                           NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
                           NSString *str = [NSString stringWithUTF8String:[data bytes]];
                           NSLog(@"str %@",str);
                           if ([httpResponse statusCode] == 200) {

                               NSLog(@"success");
                           }else{
                               NSLog(@"failed");
                           }

                       }];
}

希望这会对你有帮助!