简体   繁体   English

UIImagePNGRepresentation导致HTTP错误403

[英]UIImagePNGRepresentation causes HTTP error 403

I've got a pretty particular issue today. 我今天有一个特别的问题。 I've created a multipart/form-data header in iOS, which is then sent to a PHP script on my web server. 我在iOS中创建了一个multipart / form-data标头,然后将其发送到Web服务器上的PHP脚本。 It works fine with only strings as data, but when I attempt to append an image to the header, it returns 403. Here's the function that attempts to connect: 它只适用于字符串作为数据,但工作正常,但是当我尝试将图像附加到标题时,它返回403。这是尝试连接的函数:

func uploadImage(image: UIImage) {
    var url: NSURL = NSURL(string: "https://example.com/uploadPicture.php")!
    var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request.HTTPMethod = "POST"

    var boundary = NSString(format: "dsfghjkergsalkj")
    var contentType = NSString(format: "multipart/form-data; boundary=%@", boundary)
    request.addValue(contentType, forHTTPHeaderField: "Content-Type")
    request.timeoutInterval = 60

    var body = NSMutableData()

    body.appendData(NSString(format: "--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(NSString(format: "Content-Disposition: form-data; name=\"image-name\"\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("yay".dataUsingEncoding(NSUTF8StringEncoding)!)

    body.appendData(NSString(format: "--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(NSString(format: "Content-Type: image/png\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(NSString(format: "Content-Transfer-Encoding: binary\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(NSString(format: "Content-Disposition: form-data; name=\"profile-img\"; filename=\"profile.png\"\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(NSData(data: UIImagePNGRepresentation(image)))

    //println(NSData(data: UIImagePNGRepresentation(image)))

    body.appendData(NSString(format: "--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)

    request.HTTPBody = body

    let task = NSURLSession(configuration: .defaultSessionConfiguration(), delegate: nil, delegateQueue: NSOperationQueue.mainQueue()).dataTaskWithRequest(request) {
        data, response, error in

        if (error != nil) {
            println("Error Submitting Request: \(error)")
            return
        }

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

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

    task.resume()

}

It should return a JSON associative array that either has 'true' or 'false' under the key 'data', as shown here. 它应返回在键“数据”下具有“ true”或“ false”的JSON关联数组,如下所示。

if(isset($_FILES['profile-img'])) {
    $arr = ['data': 'true'];
} else {
    $arr = ['data': 'false'];
}

echo json_encode($arr);

Instead it returns a long list of hex bytes, which is the 403 forbidden page. 而是返回一长串的十六进制字节,即403禁止页面。

Commenting out body.appendData(NSData(data: UIImagePNGRepresentation(image))) allows the connection to work. 注释掉body.appendData(NSData(data: UIImagePNGRepresentation(image)))可使连接正常工作。

What might be causing this? 是什么原因造成的? I've tried everything I could think of. 我已经尽力想了一切。

EDIT: Here's the full PHP page, not much. 编辑:这是完整的PHP页面,数量不多。

<?php

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

if(isset($_FILES['profile-img'])) {
    $arr = ['data': 'true'];
} else {
    $arr = ['data': 'false'];
}

echo json_encode($arr);

/*$uploaddir = './uploads/';
$file = basename($_FILES['profile_img']['name']);
$uploadfile = $uploaddir . $file;

if (move_uploaded_file($_FILES['profile_img']['tmp_name'], $uploadfile)) {
    $arr = ['data': 'true'];
} else {
    $arr = ['data': 'false'];
}

echo json_encode($arr);*/

?>

You are likely not constructing a MIME multipart submission that PHP is decoding correctly. 您可能未构建PHP正确解码的MIME多部分提交。 The spec for these is here. 这些的规格在这里。

  1. Every header line must have a CRLF sequence after it. 每个标题行后面必须有一个CRLF序列。 You can accomplish this by ending your header strings with \\r\\n . 您可以通过用\\r\\n结束标题字符串来完成此操作。 There should be an extra CRLF sequence after the final header line and before the data in each part. 在最后的标题行之后和每个部分中的数据之前,应该有一个额外的CRLF序列。
  2. Your binary part (the file) has no encoding specified. 您的二进制部分(文件)未指定编码。 By default the spec assumes "7BIT" encoding, which raw binary is not a subset of. 默认情况下,规范采用“ 7BIT”编码,原始二进制文件不是该子集的子集。 Try adding the header Content-Transfer-Encoding: binary to this part. 尝试将标头Content-Transfer-Encoding: binary添加到此部分。
  3. Not necessarily a problem, but the boundary string is typically a longer string including a bunch of random characters to avoid conflicting with any actual data. 不一定是问题,但边界字符串通常是较长的字符串,其中包括一堆随机字符,以避免与任何实际数据发生冲突。 Your short sequence of asterisks is not especially strong for this. 您的星号短序列对此并不特别强。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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