Uploading images to server using ASIHTTPRequest in

2020-02-10 11:01发布

问题:

I have to upload images to server form iphone I am using ASIHTTPRequest for this. I have set a loop for uploading seven files. But after the executing only last file is uploaded can some one point out where I am getting it wrong.

I am using the below code for uploading :

for (int i=1; i<8; i++) 
    {
        NSString* filename = [NSString stringWithFormat:@"Photo%d.jpg", i];
        NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:filename];
        [request setFile:path forKey:[NSString stringWithFormat:@"file"]];
    }

    [request startAsynchronous];
    [resultView setText:@"Uploading data..."];

My Php file code is as following : 



 <?php
      if ($_FILES["file"]["error"] > 0)
        {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
        }
      else
        {
        echo "Upload: " . $_FILES["file"]["name"] . "<br />";
        echo "Type: " . $_FILES["file"]["type"] . "<br />";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

        if (file_exists("vinay/" . $_FILES["file"]["name"]))
          {
          echo $_FILES["file"]["name"] . " already exists. ";
          }
        else
          {
          move_uploaded_file($_FILES["file"]["tmp_name"],
          "vinay/" . $_FILES["file"]["name"]);
          echo "Stored in: " . "http://serverpath" . $_FILES["file"]["name"];
          }
        }
    ?> 

回答1:

You're overwriting the key called file & you need to use a queue.

Do

[self setNetworkQueue:[ASINetworkQueue queue]];
[[self networkQueue] setDelegate:self];

for (int i=1; i<8; i++) 
{
    NSString* filename = [NSString stringWithFormat:@"Photo%d.jpg", i];
    NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:filename];
    [request setFile:path forKey:[NSString stringWithFormat:@"file%d", i]];
    [[self networkQueue] addOperation:request];
}
[[self networkQueue] go];


回答2:

You're overwriting request.file, hence only the last one gets uploaded. You have to make individual requests for each file.

Or you could use [request addFile:(id)data withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key] to send multiple files in one request.