使用PHP脚本和iOS进行多个文件上传

时间:2013-02-20 07:02:46

标签: php objective-c macos

目前我正在将一个xml文件从mac上传到服务器。它工作正常。以下是代码:

osx代码

  NSString *urlString1 = @"http://username:pwd@ip/files/upload.php";


NSMutableURLRequest *request1 = [[NSMutableURLRequest alloc] init];
[request1 setURL:[NSURL URLWithString:urlString1]];
[request1 setHTTPMethod:@"POST"];



NSString *boundary1 = @"---------------------------14737809831466499882746641449";
NSString *contentType1 = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary1];
[request1 addValue:contentType1 forHTTPHeaderField:@"Content-Type"];

NSMutableData *body1 = [NSMutableData data];
[body1 appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary1] dataUsingEncoding:NSUTF8StringEncoding]];
[body1 appendData:[@"Content-Disposition: form-data; name=\"userfile\"; filename=\"data.xml\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body1 appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body1 appendData:[NSData dataWithData:xmlData]];
[body1 appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary1] dataUsingEncoding:NSUTF8StringEncoding]];
[request1 setHTTPBody:body1];
NSLog(@"xml data %@",xmlData);
NSData *returnData1 = [NSURLConnection sendSynchronousRequest:request1 returningResponse:nil error:nil];

PHP脚本

 <?php
  $target_path = "./";
  $target_path = $target_path.'data.xml';
  if(move_uploaded_file($_FILES['userfile']['tmp_name'],$target_path)) {
    echo "The file has been uploaded";
  } else{
    echo "There was an error uploading the file, please try again!";
  }
?>

现在我有一个案例,我应该添加多个文件。那么文件命名如何工作?有人请帮帮我。

1 个答案:

答案 0 :(得分:0)

我认为您可以查看PHP数组函数是否有效。我不确定XCode,但我们坚持使用Basic HTML来上传多个文件。请尝试以下代码:

可以选择多个文件,然后使用

上传
<input type='file' name='file[]' multiple>

执行上传的示例php脚本:

<html>
<title>Upload</title>
<?php
    session_start();
    $target=$_POST['directory'];
        if($target[strlen($target)-1]!='/')
                $target=$target.'/';
            $count=0;
            foreach ($_FILES['file']['name'] as $filename) 
            {
                $temp=$target;
                $tmp=$_FILES['file']['tmp_name'][$count];
                $count=$count + 1;
                $temp=$temp.basename($filename);
                move_uploaded_file($tmp,$temp);
                $temp='';
                $tmp='';
            }
    header("location:../../views/upload.php");
?>
</html>

所选文件以

的数组形式接收

$ _ FILES ['file'] ['name'] [0]存储第一个文件的名称。 $ _FILES ['file'] ['name'] [1]存储第二个文件的名称。等等。