从iOS上通过POST PHP上传文件

时间:2013-01-24 14:56:30

标签: php ios post file-upload ftp

您好我想告诉您我在做什么,因为我的PHP或我的iOS没有将文件发送到FTP服务器:S

iOS方面:

NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
NSString *nombreArchivo = @"wtthdb.db";

NSData *archivo = [NSData dataWithContentsOfFile:[[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:nombreArchivo]]];
NSLog(@"Tamaño del archivo %i",[archivo length]);

NSMutableString *post = [[NSMutableString alloc] initWithFormat:@"file=%@&filename=%@",archivo,nombreArchivo];
[post appendFormat:@"%@",archivo];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSURL *url = [NSURL URLWithString:@"http://zsoft.es/subidaios.php"];
NSMutableURLRequest *peticion = [NSMutableURLRequest requestWithURL:url];

NSURLConnection *con;
@try
{
    [peticion setHTTPMethod:@"POST"];
    [peticion setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [peticion setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [peticion setHTTPBody:postData];
    con = [NSURLConnection connectionWithRequest:peticion delegate:self];
    [con start];
}
@catch (NSException *e)
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error del servidor"
                                                    message:[NSString stringWithFormat:@"Error: %@",e]
                                                   delegate:self
                                          cancelButtonTitle:@"Aceptar"
                                          otherButtonTitles:nil];
    [alert show];
}
NSLog(@"Empezado");

这是我的PHP方面:

  <?php
if (isset($_POST['name']) && isset($_POST['filename']))
{
    $name  = $_POST['name'];
    $filename  = $_POST['filename'];
    $ftp = ftp_connect("ftp.marinesignal.com");
    ftp_login($ftp, "user", "pass");
    ftp_pasv($ftp, true);
    ftp_put($ftp,$filename,$name,FTP_BINARY);
    ftp_close($ftp);
}
 ?>

我不知道如何通过XCode调试我的PHP代码......

谢谢!

1 个答案:

答案 0 :(得分:1)

我建议你阅读这篇关于如何将UIImage上传到网页的好文章,这样你就可以了解如何准备和将文件发布到网上

http://zcentric.com/2008/08/29/post-a-uiimage-to-the-web/

然后在PHP服务器端,您应该考虑通过$ _FILES全局变量传递文件,因此您应该在这个问题上处理它们

<?php
$temporalFolder = "temporal/";

$filePath = $temporalFolder . basename( $_FILES['uploadedfile']['name']); 

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $temporalFolder)) {
    echo "The file has been uploaded";
} else{
    echo "There was an error uploading the file";
}

$name  = $_POST['name'];
$ftp = ftp_connect("ftp.marinesignal.com");
ftp_login($ftp, "user", "pass");
ftp_pasv($ftp, true);
ftp_put($ftp,$filePath,$name,FTP_BINARY);
ftp_close($ftp);

?>

希望这能让您对自己的问题有所了解