簡體   English   中英

如何將圖像文件從文檔目錄上傳到iPhone中的php服務器

[英]how to upload image file from document directory to php server in iphone

我目前正在開發類似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服務器上上傳文檔文件夾嗎?

提前致謝。

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

你可以用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中保存后必須將其解壓縮。

這是我的示例代碼

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

您需要在遞歸函數中使用/調用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
          }

    }

 }];


 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM