4

我正在尝试将音频文件发送到 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";
}

文件大小因录制的音频长度而异,但有数据。

我收到“无”的回应。

4

3 回答 3

7

调试:在 PHP 端,尝试:

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

尝试使用以下代码段代替您当前的代码。将 url (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 . "'." );

?>

我收到以下输出:

[2012 年 5 月 23 日 11:56:18] 名称 = 'thefile',文件名 = 'recording'。

我不知道为什么它不适合你。您必须缺少步骤。尝试注释掉上面引用“数据”的 url POST 代码中的两行,以查看您至少可以将名称和文件名的纯文本发送到服务器端。

祝你好运!

于 2012-05-22T23:34:58.623 回答
1

Try encoding your binary data before you send it over the pipe (and then decode when it gets to the other end). See this SO thread for ideas for Base64 encoding code.

于 2012-05-22T23:32:36.817 回答
0

迅速你可以像这样发布..

    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)")
            }

        }
    }
于 2017-01-23T04:56:27.023 回答