1

我正在尝试在服务器上的文本文件中将 label.text 上传到服务器上,这是我的代码。它没有显示任何错误,但在服务器上创建了文件,但其中没有文本。请帮忙。

NSString *post =[[NSString alloc] initWithFormat:@"VIN: %@",vincode.text];
        NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding
                              allowLossyConversion:NO];
        NSString *postLength = [NSString stringWithFormat:@"%d", [postData
                                                                  length]];
        NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init]
                                        autorelease];
        [request setURL:[NSURL URLWithString:@"Server Detail Here/upload_vin.php"]]; 
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/x-www-form-urlencoded"
       forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postData];
        NSData *urlData = [NSURLConnection sendSynchronousRequest:request
                                                returningResponse:nil error:nil];
        NSLog(@"Succeeded! Received %d bytes of data",[urlData length]);
        NSLog(@"VIN is %@",vincode.text);
        NSString *outputdata = [[NSString alloc] initWithData:urlData
                                                     encoding:NSASCIIStringEncoding];
        NSLog(@"Outputdata is %@",outputdata);
        NSURLResponse *response;
        NSError *error;
        [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
        if(error==nil)
            NSLog(@"Error is nil");
        else
            NSLog(@"Error is not nil");
        NSLog(@"success!");
PHP file::::::::::::::
    <?php
    $file = "VinCodes.txt";
    #$submitted_vincode = $_GET['VIN'] . " \n";
    $submitted_vincode = @$_POST['VIN'] . " \n";
    if(!empty($submitted_vincode)){
    $Handle = fopen($file, 'a');
        fwrite($Handle, $submitted_vincode); 
        print "Vin Code stored in file."; 
        fclose($Handle);
    }else{
        print "Vin code is missing. Try again";
    }
    ?>
4

1 回答 1

0

很多代码,这就是我所做的,(注意我上传异步):

NSURL *url = [NSURL URLWithString: @"http://..."];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:data];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[NSURLConnection sendAsynchronousRequest:request ...

顺便说一句,你确定你想要NSASCIIStringEncoding而不是NSUTF8StringEncoding

如有疑问,我会使用Charles Web Proxy(免费 30 天)来查看发送的确切内容和响应。

于 2013-03-31T15:33:18.150 回答