使用ASIHTTPRequest从IPhone将文件上传到服务器

时间:2010-07-21 15:15:56

标签: php iphone upload asihttprequest

我一直在尝试使用来自iPhone的ASIHTTPRequest库将文件( login.zip )上传到Mac OS X Snow Leopard中的内置Apache服务器。我的代码是:

 NSString *urlAddress = [[[NSString alloc] initWithString:self.uploadField.text]autorelease];

 NSURL *url = [NSURL URLWithString:urlAddress];

 ASIFormDataRequest *request;  

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);  
 NSString *documentsDirectory = [paths objectAtIndex:0];  
 NSString *dataPath = [documentsDirectory  stringByAppendingPathComponent:@"login.zip"];

 NSData *data = [[[NSData alloc] initWithContentsOfFile:dataPath] autorelease];  

 request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];  
 [request setPostValue:@"login.zip" forKey:@"file"];  
 [request setData:data forKey:@"file"];
 [request setUploadProgressDelegate:uploadProgress];
 [request setShowAccurateProgress:YES];
 [request setDelegate:self];
 [request startAsynchronous];

php代码是:

<?php $target = "upload/"; 
$target = $target . basename( $_FILES['uploaded']['name']) ; 
$ok=1; 

if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) 
{ echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded"; } 
else 
{ echo "Sorry, there was a problem uploading your file."; } ?> 

我不太明白为什么文件没有上传。如果有人可以帮助我。我连续5天坚持这个。

提前致谢 NIK

2 个答案:

答案 0 :(得分:4)

试试这个:

[request setFile:filePath forKey:@"file"]; 

或者如果您可以将您的zip文件放入NSData,就像这样

NSData *zipData = [[NSData alloc] initWithContentsOfFile:zipName];

并使用

将其发送到服务器
[request setData:zip forKey:@"file"];
服务器上的

试试这个

<?php




      $dir = "/var/www/your_directory/";

      $path = $dir . $_FILES['file']['name'];

      //move_uploaded_file($_FILES['file']['tmp_name'], $path);


     if(move_uploaded_file($_FILES['file']['tmp_name'], $path))  {
                //return ok! :)
    }
     else {
      // return -> echo"There's been a problem uploading your file. Please try again";
    }   
?>
<{1>} $_FILES['file']['name'] ['file']必须与您请求中的forKey:@"file"相同

答案 1 :(得分:0)

您正在使用的字段名称是否存在不匹配?

看起来你在iphone上使用“文件”:

[request setPostValue:@"login.zip" forKey:@"file"];  

但在服务器上“已上传”:

$target = $target . basename( $_FILES['uploaded']['name']) ; 

尝试将这些更改为相同。