【问题标题】:how to upload image file from document directory to php server in iphone如何将图像文件从文档目录上传到iphone中的php服务器
【发布时间】:2013-12-29 01:41:39
【问题描述】:

我目前正在开发画廊类型的 iPhone 应用程序。根据我的要求,我需要将所有相机捕获的图像存储到文档目录中。文档文件夹中有一些 10-20 个图像文件,之后我必须使用单个 php url 在服务器上推送该应用程序资源文档文件夹。我已附上屏幕截图,用于显示带有一些图像文件的资源文件夹。

这是我的 PHP 代码:

  $file_path = "../Gallery/";

   $file_path = $file_path . basename( $_FILES['Documents']['name']);
   if(move_uploaded_file($_FILES['Documents']['tmp_name'], $file_path)) {
       echo "Image is upload";
   } else{
       echo "Image is not Upload";
   }

有人可以帮助我如何在 php 服务器上上传文档文件夹吗?

提前致谢。

【问题讨论】:

  • 你试过我的答案了吗?

标签: php ios web-services resources


【解决方案1】:
NSData *imageData = UIImagePNGRepresentation([UIImage imageWithContentsOfFile:pathToStoreImage]);
NSString *str = [self base64StringFromData:imageData length:0];

然后你可以将str对象传递给服务器的任何参数。

在您的 .m 文件中使用 base64StringFromData 函数;

-(NSString *) base64StringFromData: (NSData *)data length: (int)length {
    unsigned long ixtext, lentext;
    long ctremaining;
    unsigned char input[3], output[4];
    short i, charsonline = 0, ctcopy;
    const unsigned char *raw;
    NSMutableString *result;

    lentext = [data length];
    if (lentext < 1)
        return @"";
    result = [NSMutableString stringWithCapacity: lentext];
    raw = [data bytes];
    ixtext = 0;

    while (true) {
        ctremaining = lentext - ixtext;
        if (ctremaining <= 0)
            break;
        for (i = 0; i < 3; i++) {
            unsigned long ix = ixtext + i;
            if (ix < lentext)
                input[i] = raw[ix];
            else
                input[i] = 0;
        }
        output[0] = (input[0] & 0xFC) >> 2;
        output[1] = ((input[0] & 0x03) << 4) | ((input[1] & 0xF0) >> 4);
        output[2] = ((input[1] & 0x0F) << 2) | ((input[2] & 0xC0) >> 6);
        output[3] = input[2] & 0x3F;
        ctcopy = 4;
        switch (ctremaining) {
            case 1:
                ctcopy = 2;
                break;
            case 2:
                ctcopy = 3;
                break;
        }

        for (i = 0; i < ctcopy; i++)
            [result appendString: [NSString stringWithFormat: @"%c", base64EncodingTable[output[i]]]];

        for (i = ctcopy; i < 4; i++)
            [result appendString: @"="];

        ixtext += 3;
        charsonline += 4;

        if ((length > 0) && (charsonline >= length))
            charsonline = 0;
    }
    return result;
}

【讨论】:

  • @Raviraj谢谢你的建议,但我没有正确理解,你能解释一下你上面的代码吗?我的 php 网址是... abc.123.com.sg/...../Mobile/Api/gallery_api.php
  • 好的,你可能有存储在 iOS 应用程序中的图像路径。获取路径并将图像转换为nsdata,进一步将数据转换为字符串。现在在您的后端服务中创建一个接受字符串的参数。在后端创建一个 POST 方法,然后将图像字符串作为参数传递
  • 但图像数量不固定..可能超过五十个。这就是为什么我将所有图像转换为 UUID 字符串值。是否只需要为服务器上的图像发送数据,什么是 base64EncodingTable ?
  • 好的@Raviraj..你能附上一些使用php url在服务器上发布图像数据的代码想法吗?
  • 我们正在使用我们创建的两个文件,这就像一个用于同步的大代码。您可以搜索一些对您有帮助的教程,但您唯一需要知道的是图像和视频是如何同步的。每当您有发布代码时,将字符串作为 UIimage 对象的参数传递
【解决方案2】:

你可以用 afnetwroking 做到这一点

-(void)saveServerData:(UIImage *)image{


NSData *imageToUpload = UIImageJPEGRepresentation(image, 1.0);
if (imageToUpload)
{


    NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
                            GameId, @"gameid"
                            , useremail, @"userid"
                            , PartIndex, @"imageposition"
                            , nil];
    NSString *url=[NSString stringWithFormat:@"%@addplayerresponse",BASE_URL];
    AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:url]];
    NSLog(@"%@",parameters);
    NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:url parameters:parameters constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
        [formData appendPartWithFileData: imageToUpload name:@"image" fileName:[NSString stringWithFormat:@"%@_%@.jpeg",appDelegate.userid,appDelegate.onlineGameId] mimeType:@"image/jpeg"];
    }];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
     {
        // NSDictionary *jsons = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
         NSLog(@"Response:%@",parameters);

         //success

     }
                                     failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         if([operation.response statusCode] == 403)
         {

             return;
         }
         NSLog(@"error: %@", [operation error]);

     }];

    [operation start];
}

}

我不认为你可以上传文件夹,你必须一次上传一张图片,或者你必须压缩文件夹并发送它,并且在 php 中你必须在保存后解压缩它。

【讨论】:

  • @souvickcse谢谢,但我没有正确获取您的代码..我不知道您在这里使用的参数是什么..您能解释一下..
【解决方案3】:

这是我的示例代码

 NSURL *nsurl =[NSURL URLWithString:urlString];  
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:nsurl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];   
 [request setURL:nsurl];  
 [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];  

 //Image  
 [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"%@\"\r\n",[fileName text]] dataUsingEncoding:NSUTF8StringEncoding]];  
 [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];  
 [body appendData:[NSData dataWithData:imageData]];  
 [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];  

【讨论】:

  • 请把 NSData 改为 NSMutableData,错误就会消失。 NSMutableData 有 base64EncodedString 方法
  • 仍然显示错误...即选择器 base64EncodedString 没有已知的实例方法
  • 我已经编辑了我的答案,请尝试一下。它必须工作
  • customerID、parameter1、客户名和文件名是什么?你在哪里设置标签?你在服务器上同时发送图像数据和文本吗?
  • 嘿,使用上面的代码,我得到了 returnData 0x1247e5d0 但该响应数据的响应字符串仍然显示“图像未上传”
【解决方案4】:

您需要在递归函数中使用/调用 API 来完成此操作。

服务器端代码

//Create a folder named images in your server where you want to upload the image.
 // And Create a PHP file and use below code .


 <?php
 $uploaddir = 'images/';
 $ran = rand () ;

 $file = basename($_FILES['userfile']['name']);
 $uploadfile = $uploaddir .$ran.$file;

 if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
 echo "www.host.com/.../images/{$uploadfile}";
 }
 ?>

应用端代码

 - (IBAction)uploadClicked:(id)sender
 {

 [self  UploadTheImageNow:0];

 }

下面的代码是递归函数,它将一直持续到所有图像上传完成。

-(void)UploadTheImageNow:(NSInteger)count
 {

 // UIImage *updatedImage=[UIImage ImageNamed:@" Your Image name / you can get from array"];
 UIImage *updatedImage=[UIImage ImageNamed:[yourArray ObjectAtIndex:ic]];
 NSData *imageData = UIImageJPEGRepresentation(updatedImage, 90);
 NSString *urlString = @"your URL link";
 NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
 [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:@"rn--%@rn",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
 [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name="userfile"; filename="ipodfile.jpg"rn"] dataUsingEncoding:NSUTF8StringEncoding]];
 [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-streamrnrn"] dataUsingEncoding:NSUTF8StringEncoding]];
 [body appendData:[NSData dataWithData:imageData]];
 [body appendData:[[NSString stringWithFormat:@"rn--%@--rn",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
 [request setHTTPBody:body];


 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
 completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
 {
   if ([(NSHTTPURLResponse *)response statusCode]==200)
    {
      id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
      NSLog(@"Finished with jsonObject %@", jsonObject);
      count++;
      if(count<20)
         {
           [self  UploadTheImageNow:count];
         }
        else
          {
            // Finished Uploading all Images
          }

    }

 }];


 }

【讨论】:

    猜你喜欢
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-29
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多