从 iPhone 应用程序上传图像

发布于 2024-10-08 11:19:46 字数 5869 浏览 0 评论 0原文

我正在尝试从 iPhone 应用程序将图像上传到服务器

,用于上传图像的 PHP 代码如下

if(isset($_POST['insertImage']))
{                   //INSERT IMAGE -------------------
     $method=safeData($_POST['insertImage']);
    if($method=='true')
    {
        if(isset($_POST['userId']))
        {

            if(isset($_FILES['imageFile']))
            {

            if($_FILES['imageFile']['type']=="image/gif" || $_FILES['imageFile']['type']=="image/bmp" || $_FILES['imageFile']['type']=='image/jpeg' || $_FILES['imageFile']['type']=='image/jpg' || $_FILES['imageFile']['type']=='image/png')
            {
                if($_FILES['imageFile']['size']<=5250000)
                {
                                                                                $userId=safeData($_POST['userId']);
                    $newImgName=rand()."a".time().".".findexts($_FILES["imageFile"]["name"]);                       imgPath="./../admin/images/";
                    move_uploaded_file($_FILES['imageFile']['tmp_name'],$imgPath.$newImgName);
                    $data.=saveImageInfo($userId,$newImgName);  
                }
                    else
                {
                  $data.="<List><ResponseCode>405</ResponseCode><Message>Maximum image size should not be more than 5mb </List>";   
                }
            }
            else
            {
                $data.="<List><ResponseCode>405</ResponseCode><Message>Invalid image format. only png,jpg,bmp formats supported</Message></List>";                                                      }
            }
            else
            {
                $data.="<List><ResponseCode>405</ResponseCode><Message>imageFile method not found</Message></List>";             
            }
                                                                    }
        else
        {
            $data.="<List><ResponseCode>405</ResponseCode><Message>userId method not found</Message></List>";   
        }
    }
    else
    {
        $data.="<List><ResponseCode>405</ResponseCode><Message>invalid insertImage argument</Message></List>";              
    }
}

,我使用以下代码从上面的代码将图像上传到服务器

+(NSData *)setUserImage:(NSData *)userImageData UserId:(int)UserId
{
    NSString *result;
    NSData *responseData;
    @try {
        NSURL *url = [[NSURL alloc] initWithString:webAddress]; 
        NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:url];
        [req setHTTPMethod:@"POST"];

        [req setValue:@"multipart/form-data; boundary=*****" forHTTPHeaderField:@"Content-Type"];//

        NSMutableData *postBody = [NSMutableData data];
        NSString *stringBoundary = [NSString stringWithString:@"*****"];

        [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
        [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"insertImage\"\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
        [postBody appendData:[[NSString stringWithFormat:@"true"] dataUsingEncoding:NSASCIIStringEncoding]];
        [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];


        [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
        [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userId\"\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
        [postBody appendData:[[NSString stringWithFormat:@"%d",UserId] dataUsingEncoding:NSASCIIStringEncoding]];
        [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];

        [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
        [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"imageFile\"; filename=\"myimagefile.png\"\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];

        //[postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"imageFile\"; filename=\"myimagefile.png\"\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
        [postBody appendData:[NSData dataWithData:userImageData]];// dataUsingEncoding:NSASCIIStringEncoding]];
        [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];

        [req setHTTPBody: postBody];//putParams];   

        NSHTTPURLResponse* response = nil;  
        NSError* error = [[[NSError alloc] init] autorelease];  

        responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];  
        result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        if(isInDebugMode)
            NSLog(@"Result: %@", result);

        [url release];
        [req release];

        IceCreamManFinderAppDelegate *delegate1=(IceCreamManFinderAppDelegate *)[UIApplication sharedApplication].delegate;
        if(error.domain!=nil)
        {
            NSString *errorDesc=[[error userInfo] objectForKey:@"NSLocalizedDescription"];
            delegate1.globalErrorMessage=errorDesc;
            return nil;
        }
        else
        {
            delegate1.globalErrorMessage=nil;
        }
    }
    @catch (NSException* ex) {
        NSLog(@"Error: %@",ex);
    }
    return responseData;
}

,我从服务器得到以下响应

图像格式无效。只有 png、jpg、bmp 格式

我尝试了很多但没有成功。

请指出我哪里错了?

i am trying to upload a image to server from iPhone application

PHP code for upload image is following

if(isset($_POST['insertImage']))
{                   //INSERT IMAGE -------------------
     $method=safeData($_POST['insertImage']);
    if($method=='true')
    {
        if(isset($_POST['userId']))
        {

            if(isset($_FILES['imageFile']))
            {

            if($_FILES['imageFile']['type']=="image/gif" || $_FILES['imageFile']['type']=="image/bmp" || $_FILES['imageFile']['type']=='image/jpeg' || $_FILES['imageFile']['type']=='image/jpg' || $_FILES['imageFile']['type']=='image/png')
            {
                if($_FILES['imageFile']['size']<=5250000)
                {
                                                                                $userId=safeData($_POST['userId']);
                    $newImgName=rand()."a".time().".".findexts($_FILES["imageFile"]["name"]);                       imgPath="./../admin/images/";
                    move_uploaded_file($_FILES['imageFile']['tmp_name'],$imgPath.$newImgName);
                    $data.=saveImageInfo($userId,$newImgName);  
                }
                    else
                {
                  $data.="<List><ResponseCode>405</ResponseCode><Message>Maximum image size should not be more than 5mb </List>";   
                }
            }
            else
            {
                $data.="<List><ResponseCode>405</ResponseCode><Message>Invalid image format. only png,jpg,bmp formats supported</Message></List>";                                                      }
            }
            else
            {
                $data.="<List><ResponseCode>405</ResponseCode><Message>imageFile method not found</Message></List>";             
            }
                                                                    }
        else
        {
            $data.="<List><ResponseCode>405</ResponseCode><Message>userId method not found</Message></List>";   
        }
    }
    else
    {
        $data.="<List><ResponseCode>405</ResponseCode><Message>invalid insertImage argument</Message></List>";              
    }
}

and I used following code to upload image to server

+(NSData *)setUserImage:(NSData *)userImageData UserId:(int)UserId
{
    NSString *result;
    NSData *responseData;
    @try {
        NSURL *url = [[NSURL alloc] initWithString:webAddress]; 
        NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:url];
        [req setHTTPMethod:@"POST"];

        [req setValue:@"multipart/form-data; boundary=*****" forHTTPHeaderField:@"Content-Type"];//

        NSMutableData *postBody = [NSMutableData data];
        NSString *stringBoundary = [NSString stringWithString:@"*****"];

        [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
        [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"insertImage\"\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
        [postBody appendData:[[NSString stringWithFormat:@"true"] dataUsingEncoding:NSASCIIStringEncoding]];
        [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];


        [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
        [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userId\"\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
        [postBody appendData:[[NSString stringWithFormat:@"%d",UserId] dataUsingEncoding:NSASCIIStringEncoding]];
        [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];

        [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
        [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"imageFile\"; filename=\"myimagefile.png\"\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];

        //[postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"imageFile\"; filename=\"myimagefile.png\"\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
        [postBody appendData:[NSData dataWithData:userImageData]];// dataUsingEncoding:NSASCIIStringEncoding]];
        [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];

        [req setHTTPBody: postBody];//putParams];   

        NSHTTPURLResponse* response = nil;  
        NSError* error = [[[NSError alloc] init] autorelease];  

        responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];  
        result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        if(isInDebugMode)
            NSLog(@"Result: %@", result);

        [url release];
        [req release];

        IceCreamManFinderAppDelegate *delegate1=(IceCreamManFinderAppDelegate *)[UIApplication sharedApplication].delegate;
        if(error.domain!=nil)
        {
            NSString *errorDesc=[[error userInfo] objectForKey:@"NSLocalizedDescription"];
            delegate1.globalErrorMessage=errorDesc;
            return nil;
        }
        else
        {
            delegate1.globalErrorMessage=nil;
        }
    }
    @catch (NSException* ex) {
        NSLog(@"Error: %@",ex);
    }
    return responseData;
}

from above code i get following response from server

Invalid image format. only png,jpg,bmp formats

i tried lot but not success.

Please suggest where i am wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浮云落日 2024-10-15 11:19:46

您编写的服务器代码仅接受具有某些指定内容类型的数据,但您从未将内容类型添加到数据中。只需为您的图像数据发出正确的内容类型:

// Emit the content type here as well
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"imageFile\"; filename=\"myimagefile.png\"\r\nContent-Type: image/png\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];

[postBody appendData:[NSData dataWithData:userImageData]];
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];

错误实际上是从您自己的服务器响应返回的,因此只需遵循服务器代码上的控制流程即可找到原因。

You wrote the server code to only accept data with certain specified content types, but then you never added the content type to your data. Simply emit the correct content type for your image data:

// Emit the content type here as well
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"imageFile\"; filename=\"myimagefile.png\"\r\nContent-Type: image/png\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];

[postBody appendData:[NSData dataWithData:userImageData]];
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];

The error is actually coming back from your own server response, so simply following the flow of control on your server code gives you the cause.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文