上传文件到iPhone上的FTP服务器(Upload File to FTP Server on i

2019-06-18 09:47发布

我想实现的是上传文件到FTP服务器的逻辑。

我在iPhone开发是新,所以想弄清楚首选方法。 浏览可用的API这个任务我设法找到使用CFNetwork的唯一代码后(即貌似不客观的基于C)。

也有使用NSURL等基于C语言它们是目标网址加载系统。

所以,我的问题:是否可以使用URL加载系统来实现文件上传到FTP服务器?

谢谢。

Answer 1:

我使用PHP页面的文件发布到并有PHP处理上传....

此代码是用来上传一张照片,但它可以适应任何文件的工作。

PHP代码:

<?php
$uploaddir = 'photos/';
$file = basename($_FILES['userfile']['name']);
$uploadfile = $uploaddir . $file;

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "OK";
} else {
    echo "ERROR";
}

?>

iPhone代码:

- (BOOL)uploadImage:(NSData *)imageData filename:(NSString *)filename{


    NSString *urlString = @"http://www.yourdomainName.com/yourPHPPage.php";

    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:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n",filename]] 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]];
    [request setHTTPBody:body];

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding] autorelease];

    return ([returnString isEqualToString:@"OK"]);
}

方法调用:

[self uploadImage:UIImageJPEGRepresentation(imageView.image, 1.0) filename:imageName];


文章来源: Upload File to FTP Server on iPhone