使用POST将文件从iOS发送到PHP

时间:2012-05-22 23:23:54

标签: php iphone objective-c xcode

我正在尝试将音频文件发送到PHP服务器。这是Objective-C代码:

NSData *data = [NSData dataWithContentsOfFile:filePath];

NSLog(@"File Size: %i",[data length]);

//set up request
NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];

//required xtra info
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

//body of the post
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"thefile\"; filename=\"recording\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:data];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:postbody];
apiConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

这是PHP代码:

if (is_uploaded_file($_FILES['thefile']['tmp_name'])) {
    echo "FILE NAME: ".$_FILES['thefile']['name'];
} else {
    echo "Nothing";
}

文件大小取决于录制的音频长度,但有数据。

我得到了“没什么”的回应。

3 个答案:

答案 0 :(得分:7)

调试:在PHP端,尝试:

$file = $_POST['name'];
echo $file

尝试使用以下代码段代替当前代码。将网址(www.yourWebAddress.com)和脚本名称更改为适合您问题的值。

NSData *data = [NSData dataWithContentsOfFile:filePath];
NSMutableString *urlString = [[NSMutableString alloc] initWithFormat:@"name=thefile&&filename=recording"];
[urlString appendFormat:@"%@", data];
NSData *postData = [urlString dataUsingEncoding:NSASCIIStringEncoding 
                                   allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSString *baseurl = @"https://www.yourWebAddress.com/yourServerScript.php"; 

NSURL *url = [NSURL URLWithString:baseurl];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod: @"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
[urlRequest setValue:@"application/x-www-form-urlencoded" 
          forHTTPHeaderField:@"Content-Type"];
[urlRequest setHTTPBody:postData];

NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
[connection start];

NSLog(@"Started!");

在服务器端,我有以下代码:

<?php

    $name  = $_POST['name'];
    $filename  = $_POST['filename'];
    echo "Name = '" . $name . "', filename = '" . $filename . "'.";

    error_log ( "Name = '" . $name . "', filename = '" . $filename . "'." );

?>

我收到了以下输出:

[23-May-2012 11:56:18] Name ='thefile',filename ='recording'。

我不知道为什么它不适合你。你必须缺少一步。尝试在上面引用'data'的url POST代码中注释掉两行,看看你至少可以得到服务器端的名称和文件名的纯文本。

祝你好运!

答案 1 :(得分:1)

尝试对二进制数据进行编码,然后再通过管道发送(然后在到达另一端时进行解码)。有关Base64编码代码的建议,请参阅this SO thread

答案 2 :(得分:0)

在swift中你可以像这样发帖..

    func wsPostData(apiString: String, jsonData: String) -> Void
    {
         //apiString means base URL
        let postData = jsonData.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)
        let postLenth = "\(UInt((postData?.length)!))"
        let request = NSMutableURLRequest()
        request.URL = NSURL(string: apiString)
        request.HTTPMethod = "POST"
        request.setValue(postLenth, forHTTPHeaderField: "Content-Lenth")
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.HTTPBody = postData
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response: NSURLResponse?, data: NSData?, error:NSError?) in

            print("response\(response)")
            var dict:NSDictionary!
            do {
                dict = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: AnyObject]
                print(" responce data is \(dict)")
            }
            catch let error as NSError
            {
                print("Something went wrong\(error)")
            }

        }
    }