在 iOS 应用程序中生成的 png 文件丢失了 mimetype

Lost mimetype of png file generated in the iOS app

在 iOS 应用程序中生成的 png 文件在使用 NSURLSessionUploadTask 发送时丢失了 mime/type。

正在创建 PNG 文件数据:

   var imageData = UIImagePNGRepresentation(savedImage)

设置内容类型:

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

php 文件的输出:

$ftmp = $_FILES['image']['tmp_name'];
$imageinfo = getimagesize($ftmp);
print_r($imageinfo);

显示所有字段但不显示类型!该字段为空。我该如何解决?

[名称] => img2015-09-29 18:44:57 +0000.png\n
[类型] => \n
[tmp_name] => C:\Windows\Temp\php5B91.tmp\n
[错误] => 0\n
[尺寸] => 2486131\n

输出

    Optional("________Array\n(\n   
[add] => Test\n    
[content_type] => 3\n    
[tok] => CKISTTDE\n)\n________Array\n(\n   
[image] => Array\n        (\n           
[name] => img2015-09-29 18:44:57 +0000.png\n            
[type] => \n            
[tmp_name] => C:\Windows\Temp\php5B91.tmp\n         
[error] => 0\n           
[size] => 2486131\n        )\n\n)\n
Image Type is:3
File is of the wrong type:  is not supported.
Sorry, there was an error uploading your file.")

PHP

<?php
    $data = file_get_contents('php://input');
    print_r($data);

    echo "________";
    print_r($_POST);
    echo "________";
    print_r($_FILES);





    if (ctype_digit($_POST['content_type'])) {

    $imagetype = $_POST['content_type'];
    echo "Image Type is:".$imagetype;
    }
    else {
        echo "Illegal Image Type. .jpg and .png formats are accepted.";
        //return;
    }

    $ftmp = $_FILES['image']['tmp_name'];

    $imageinfo = getimagesize($ftmp);
    print_r($imageinfo);

    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["image"]["name"]);

    $happyimages = array("image/jpeg","image/png","image/tga");
    if (!in_array($imageinfo["mime"],$happyimages)) { 
            echo 'File is of the wrong type: '.$imageinfo["mime"].' is not supported.';
    }
    else{
        echo "File type is: ".  $imageinfo["mime"]; 
    }


    if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["image"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }



?>

SWIFT:

static func uploadImage(image:UIImage,token:String, imageType:String, callback:((message:String?, error:String?)->Void))->NSURLSessionTask{



            let filename = "\(NSDate()).png";
            image.saveToPNG(filename)

            let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as!   String
            let destinationPath = documentsPath.stringByAppendingPathComponent(filename)

            let savedImage = UIImage(data: NSData(contentsOfFile: destinationPath)!)
            var imageData = UIImagePNGRepresentation(savedImage)
            imageData = NSData(data: imageData)

            var request = NSMutableURLRequest(URL: NSURL(string:APIKeys.url.rawValue)!)
            var session = NSURLSession.sharedSession()

            request.HTTPMethod = "POST"

            var boundary = NSString(format: "---------------------------14737809831466499882746641449")
            var contentType = NSString(format: "multipart/form-data; boundary=%@",boundary)
            //  println("Content Type \(contentType)")
            request.addValue(contentType as String, forHTTPHeaderField: "Content-Type")

            var body = NSMutableData.alloc()

            // Add
            body.appendData(NSString(format: "\r\n--%@\r\n",boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
            body.appendData(NSString(format:"Content-Disposition: form-data; name=\"add\"\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
            body.appendData("Test".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)

            // Image Type
            body.appendData(NSString(format: "\r\n--%@\r\n",boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
            body.appendData(NSString(format:"Content-Disposition: form-data; name=\"content_type\"\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
            body.appendData(imageType.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)

            // Token
            body.appendData(NSString(format: "\r\n--%@\r\n",boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
            body.appendData(NSString(format:"Content-Disposition: form-data; name=\"tok\"\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
            body.appendData(token.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)

           // println("request \(request)")
            //Other fields

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


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


            //  session.uploadTaskWithRequest(request, fromData: body)
           // NSURLSessionUploadTask()
            let task = session.uploadTaskWithRequest(request, fromData: body, completionHandler: { (data, response, error) -> Void in
                  var returnString:String?
                if let data = data, string = NSString(data: data, encoding: NSUTF8StringEncoding) {
                    returnString = string as String
                }

                var errorText:String?
                if let error = error{
                    errorText = error.description
                }

                callback(message: returnString, error: errorText)


                })
            task.resume()

        return task
    }

看来问题出在服务器端。具体在 php.ini max_upload 设置中。