简体   繁体   中英

NSURLSessionUploadTask returns HTTP 403 Error Page

I've facing a pretty odd issue. I'm attempting to upload an image to a PHP script. The build compiles without errors, which is what I had expected, but when the session is actually completed, it returns with an HTTP error 403. I'm aware that 403 is "Forbidden", but I have no idea is to what might be causing the error. Here's the session.

func uploadFile(fileData: NSData) {
    var request: NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: "https://www.codekaufman.com/file.php")!)
    request.HTTPMethod = "POST"

    let session = NSURLSession(configuration: .defaultSessionConfiguration())

    let uploadTask = session.uploadTaskWithRequest(request, fromData: fileData, completionHandler:{
        data, response, error in
        if error != nil {
            println(error)
            return
        }

        println(response.description)
        println()

        var err: NSError?
        var receivedData: [String: AnyObject]!
        receivedData = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? [String: AnyObject]

        if(receivedData != nil) {
            println(receivedData)
        } else {
            println("No data recieved.")
        }

    })

    uploadTask.resume()
}

Here's the PHP script, it's nothing special.

<?php

error_reporting(E_ALL);
ini_set('display errors', 1);

if(isset($_FILES['file'])) {
    echo json_encode(array('status' => 'true'));   
} else {
    echo json_encode(array('status' => 'false'));  
}

?>

Lastly here's the response.

<NSHTTPURLResponse: 0x7ff4f062bd10> { URL: https://www.codekaufman.com/file.php } { status code: 403, headers {
    "Accept-Ranges" = bytes;
    Connection = "Keep-Alive";
    "Content-Length" = 1551;
    "Content-Type" = "text/html";
    Date = "Fri, 13 Feb 2015 08:05:55 GMT";
    "Keep-Alive" = "timeout=10, max=200";
    Server = Apache;
} }

I should note the console displays "No data received." I've asked around in the SO chat room 'NSChat', and we've played around with attempting to fix it. Although we didn't fix it, we have discovered that it does NOT receive an auth challenge.

Furthermore, I have no idea what to do. Any help is much appreciated. Thanks.

Unfortunately, while I cannot say why this works, I found that adding the line

request.addValue("application/form-data", forHTTPHeaderField: "Content-Type")

solved all of my issues. The server responds with 200, and I receive the JSON response as expected. Thanks to those who had attempted to help, although not answering my question, you guys brought some important points to my attention.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM