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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10711481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 00:23:36  来源:igfitidea点击:

Sending file from iOS to PHP using POST

phpiphoneobjective-cxcode

提问by Chris

I'm trying to send an audio file to a PHP server. Here is the Objective-C code:

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

And here is the PHP code:

这是 PHP 代码:

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

The File Size varies depending on the length of audio being recorded, but there is data.

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

I'm getting a response of "Nothing".

我收到“没什么”的回应。

回答by Sunny

To debug: on the PHP side, try:

调试:在 PHP 端,尝试:

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

Try the following code segment in place of your current code. Change the url (www.yourWebAddress.com) and script name to appropriate values for your problem.

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

On the server end, I have the following code:

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

<?php

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

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

?>

I received the following output:

我收到以下输出:

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

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

I don't know why it is not working for you. You must have a missing step. Try commenting out the two lines in the url POST code above that references 'data' to see that you can get at the least the plain text for name and filename to your server end.

我不知道为什么它不适合你。你肯定少了一步。尝试注释掉上面引用“数据”的 url POST 代码中的两行,以查看您至少可以获得服务器端的名称和文件名的纯文本。

Good luck!

祝你好运!

回答by Alex Reynolds

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

在通过管道发送二进制数据之前尝试对其进行编码(然后在它到达另一端时进行解码)。有关Base64 编码代码的想法,请参阅此 SO 线程

回答by kalpesh

In swift you can post like this..

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

        }
    }