Swift上传图像状态代码200错误

时间:2016-02-03 12:40:11

标签: ios swift swift2 image-uploading

您好我的图片上传代码看起来不错,但提供了200个错误代码状态,并且不会将图片上传到服务器我的代码。

import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate {
    @IBOutlet weak var myImageView: UIImageView!
    @IBOutlet weak var imageUploadProgressView: UIProgressView!
    @IBOutlet weak var progressLabel: UILabel!
    @IBOutlet weak var uploadButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func uploadButtonTapped(sender: AnyObject) {

        let myPickerController = UIImagePickerController()
        myPickerController.delegate = self;
        myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary

        self.presentViewController(myPickerController, animated: true, completion: nil)

    }


    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
    {
        myImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage

        myImageView.backgroundColor = UIColor.clearColor()
        self.dismissViewControllerAnimated(true, completion: nil)

        uploadImage()

    }




    func uploadImage()
    {
        let imageData = UIImageJPEGRepresentation(myImageView.image!, 1)

        if(imageData == nil ) { return }

        self.uploadButton.enabled = false

        let uploadScriptUrl = NSURL(string:"http://www.bla.com/upload.php")
        let request = NSMutableURLRequest(URL: uploadScriptUrl!)
        request.HTTPMethod = "POST"
        request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")

        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())

        let task = session.uploadTaskWithRequest(request, fromData: imageData!)
        task.resume()

    }

    func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?)
    {
        print("didCompleteWithError")

        let myAlert = UIAlertView(title: "Alert", message: error?.localizedDescription, delegate: nil, cancelButtonTitle: "Ok")
        myAlert.show()

        self.uploadButton.enabled = true

    }
    func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64)
    {
        print("didSendBodyData")
        let uploadProgress:Float = Float(totalBytesSent) / Float(totalBytesExpectedToSend)

        imageUploadProgressView.progress = uploadProgress
        let progressPercent = Int(uploadProgress*100)
        progressLabel.text = "\(progressPercent)%"
        print(uploadProgress)
    }
    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void)
    {
        print("didReceiveResponse")
        print(response);
        self.uploadButton.enabled = true
    }
    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData)
    {
        print("didReceiveData")
          print(data);
    }

}

我的upload.php

<?

$target_dir = "upload";

if(!file_exists($target_dir))
{
mkdir($target_dir, 0777, true);
}

$target_dir = $target_dir . "/" . basename($_FILES["file"]["name"]);

if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir)) {
echo json_encode([
"Message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.",
"Status" => "OK"
]);

} else {

echo json_encode([
"Message" => "Sorry, there was an error uploading your file.",
"Status" => "Error"
]);
}

?>

Xcode上传进度稍后会在此处显示响应错误;

<NSHTTPURLResponse: 0x7fbbd171bac0> { URL: http://www.bla.com/upload.php } { status code: 200, headers {
    Connection = "Keep-Alive";
    "Content-Type" = "text/html; charset=UTF-8";
    Date = "Wed, 03 Feb 2016 12:36:18 GMT";
    "Keep-Alive" = "timeout=5, max=100";
    Server = Apache;
    "Transfer-Encoding" = Identity;
    "X-Powered-By" = "PHP/5.6.17";
} }

感谢您的帮助。我尝试了一切,但我没有解决它。

谢谢!

0 个答案:

没有答案