Monday, October 23, 2023
HomeiOS Developmentios - NSURL POST file add activity doesn't add to net server

ios – NSURL POST file add activity doesn’t add to net server


I’m making an attempt to add a textual content file to an internet server from an iOS software. I’ve written an goal C methodology to deal with the add request and a PHP file to deal with the POST request on the server. I’ve additionally written a small HTML web page to check the add from a browser (which is working superb utilizing the identical PHP file). When the iOS App runs it ought to add a textual content file (which is empty ie 0 bytes in dimension) to a specified folder on the internet server, and though the debug window exhibits the response as success(200) the file will not be uploaded.

Right here is the Goal C methodology

    + (void)fileUpload{
        NSString *localFilePath = [self GetTokenFilePath];
        NSURL *localFile = [NSURL fileURLWithPath:localFilePath];
        NSData *knowledge = [[NSData alloc] initWithContentsOfFile:localFilePath];
        NSString *filename = [self GetTokenFilename];
        // Arrange the physique of the POST request.

        // This boundary serves as a separator between one type subject and the following.
        // It should not seem anyplace throughout the precise knowledge that you simply intend to
        // add.
        NSString * boundary = @"---------------------------14737809831466499882746641449";

        // Physique of the POST methodology
        NSMutableData * physique = [NSMutableData data];
    
        // The physique should begin with the boundary preceded by two hyphens, adopted
        // by a carriage return and newline pair.
        //
        // Discover that we prepend two further hyphens to the boundary when
        // we truly use it as a part of the physique knowledge.
        //
        [body appendData:[[NSString stringWithFormat:@"rn--%@rn",boundary]     dataUsingEncoding:NSUTF8StringEncoding]];
    
        // That is adopted by a sequence of headers for the primary subject after which
        // TWO CR-LF pairs. set tag-name to submit add
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data;      name="file"; filename="%@.txt"rn", filename] dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[@"Content-Type: application/octet-streamrnrn" dataUsingEncoding:NSUTF8StringEncoding]];
        // Subsequent is the precise knowledge for that subject (referred to as "tag_name") adopted by
        // a CR-LF pair, a boundary, and one other CR-LF pair.
        [body appendData:[NSData dataWithData:data]];
    
        // Shut the request physique with one final boundary with two
        // further hyphens prepended **and** two further hyphens appended.
        [body appendData:[[NSString stringWithFormat:@"rn--%@--rn", boundary]     dataUsingEncoding:NSUTF8StringEncoding]];

    
        // Knowledge importing activity.
        NSURL * url = [NSURL URLWithString:@"https://MY_URL.co.uk/Upload.php"];
        NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
        NSString * contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
        [request addValue:contentType forHTTPHeaderField:@"Content-Type"];
        request.HTTPMethod = @"POST";
        request.HTTPBody = physique;
    
        /*------------------*/
        NSURLSession *session = [NSURLSession sharedSession];
    
        // Create a NSURLSessionUploadTask object to Add knowledge for a jpg picture.
        NSURLSessionUploadTask *activity = [session uploadTaskWithRequest:request fromFile:localFile completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
            if (error == nil) {
                // Upload success.
                NSLog(@"upload file:%@",localFile);
                NSLog(@"upload success:%@",[[NSString alloc] initWithData:knowledge encoding:NSUTF8StringEncoding]);
                NSLog(@"add response:%@",response);
                // Replace person defaults to indicate success on token add.
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                [defaults setBool:TRUE forKey:@"TOKEN_UPLOAD_SUCCESS"];
            } else {
                // Add fail.
                NSLog(@"add error:%@",error);
                NSLog(@"add response:%@",response);
                // Replace person defaults to indicate success on token add.
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                [defaults setBool:FALSE forKey:@"TOKEN_UPLOAD_SUCCESS"];
            }
        
        }];
        [task resume];
    
     }

Right here is the PHP file I exploit on the server finish

    <?php

    print_r($_POST);
    echo "<br>";

    //phpinfo();

    // file properties
    $file = $_FILES['file'];
    $file_name = $_FILES['file']['name'];
    $file_tmp = $_FILES['file']['tmp_name'];
    $file_size = $_FILES['file']['size'];
    $file_error = $_FILES['file']['error'];
    $file_type = $_FILES['file']['type'];
    echo "File title = ".$file_name."<br>";
    echo "File dimension = ".$file_size."<br>";
    echo "File error = ".$file_error."<br>";
    //print_r($file);


    //work out the file extension

    $file_ext = explode('.' , $file_name );
    $file_actual_ext = strtolower(finish($file_ext));
    echo "File Extension = ".$file_actual_ext."<br>";
    //echo $file_actual_ext;

    $allowed = array('txt', 'csv');
    print_r($allowed);
    echo "<br>";

    if(in_array($file_actual_ext,$allowed)) {
        echo "File sort is allowed"."<br>";
        if($file_error === 0) {
            if($file_size <= 1048576) {
                $file_destination = "TokensV11/".$file_name;
                echo "File Vacation spot = ".$file_destination."<br>";
                    if(move_uploaded_file($file_tmp, $file_destination)) {
                        echo "The file has been uploaded sucessfully"."<br>";
                    }else{
                        echo "The file was not moved to vacation spot"."<br>";
                    }
                }else{
                    echo "The file dimension is just too giant"."<br>";
                    }
            }else{
                echo "There was an error importing your file"."<br>";
                }
    }else {
            echo "You can't add recordsdata of this kind or no file was specified"."<br>";
            }

    ?>

Right here is the output pattern from the debug window in Xcode

2023-07-25 12:39:26.855874+0100 BikerCafe[3036:86717] add file:file:///Customers/stephencox/Library/Developer/CoreSimulator/Gadgets/5246C453-B5BF-4F6E-B4BD-E5121A382E87/knowledge/Containers/Knowledge/Software/MYFILE.txt
2023-07-25 12:39:28.238222+0100 BikerCafe[3036:86717] add success:The PHP script has began<br>File title = <br>File dimension = <br>File error = <br>File Extension = <br>Array
(
    [0] => txt
    [1] => csv
    [2] => png
)
<br>File Vacation spot = TokensV11/<br>
2023-07-25 12:39:30.723756+0100 BikerCafe[3036:86717] add response:<NSHTTPURLResponse: 0x6000010e7f60> { URL: https://tokens.ukbikercafes.co.uk/TokenUpload.php } { Standing Code: 200, Headers {
    "Content material-Encoding" =     (
        gzip
    );
    "Content material-Kind" =     (
        "textual content/html; charset=UTF-8"
    );
    Date =     (
        "Tue, 25 Jul 2023 11:39:23 GMT"
    );
    Server =     (
        Apache
    );
    "x-powered-by" =     (
        "PHP/7.4.33"
    );
} }



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments