如何将图像从我的iOS应用程序上传到PHP服务器?

时间:2015-05-15 12:14:49

标签: php ios swift image-uploading

我不知道php和swift很好所以你能帮帮我吗?我有一台服务器:cs.hisarschool.k12.tr/ecs.php,这是代码:

<?php

$firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];
$userId = $_POST["userId"];
$target_dir = "/var/www/html/uploads";

// $myfile = fopen($target_dir, "w");

if(!file_exists($target_dir))

{
    echo "creating directory";
    mkdir($target_dir, 0555, true);
}

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

$target_file = $target_dir . "/sc.jpg";

if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {

    echo json_encode([
    "Message" => "The file " . basename($_FILES["file"]["name"]) . " has been    uploaded.",
    "Status" => "OK",
    "userId" => $_REQUEST["userId"]
    ]);

} else {

    echo json_encode([
    "Message" => "Sorry, there was an error uploading your file(" .   basename($_FILES["filename"][name])  . ").",
    "Status" => "Error",
    "userId" => $_REQUEST["userId"]
    ]);
}

?>

快速代码:

//
//  ViewController.swift
//  application
//
//  Created by kerem on 13/05/15.
//  Copyright (c) 2015 kerem. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBOutlet weak var myImageView: UIImageView!

    @IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!

    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) {
        myImageUploadRequest()
    }
    @IBAction func selectPhotoButtonTapped(sender : AnyObject) {
        var myPickerController = UIImagePickerController()
        myPickerController.delegate = self
        myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        self.presentViewController(myPickerController,animated:true, completion : nil)
    }
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {

        myImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    //buraya yaz
    func myImageUploadRequest() {
        println("1")
        let myUrl = NSURL(string : "cs.hisarschool.k12.tr/esc.php")//buraya
        let request = NSMutableURLRequest(URL:myUrl!);
        request.HTTPMethod = "POST";
        let param = [
            "firstName" : "Kerem",
            "lastName" : "Guventurk",
            "userId" : "dreamkiller"
        ]
        let boundary = generateBoundaryString()

        request.setValue("multipart/form-data; boundary=\(boundary)",forHTTPHeaderField:"Content-Type")
        let imageData = UIImageJPEGRepresentation(myImageView.image, 1)
        if (imageData == nil) {
            return;
        }
        request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData, boundary : boundary)
        myActivityIndicator.startAnimating();

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data,response,error in
            if error != nil {
                println("error=\(error)")
                return
            }
            println("******** response = \(response)")
            let responseString = NSString(data:data,encoding:NSUTF8StringEncoding)
            println("******** response data = \(responseString!)")

            var err: NSError?
            var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary

            dispatch_async(dispatch_get_main_queue(),{
                self.myActivityIndicator.stopAnimating()
                self.myImageView.image = nil;
            });
        }
        task.resume()
    }
    //isim burada
    func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
        println("2")
        var body = NSMutableData();

        if parameters != nil {
            for (key, value) in parameters! {
                body.appendString("–\(boundary)\r\n")
                body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString("\(value)\r\n")
            }
        }

        let filename = "user-profile.jpg"

        let mimetype = "image/jpg"

        body.appendString("–\(boundary)\r\n")
        body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
        body.appendString("Content-Type: \(mimetype)\r\n\r\n")
        body.appendData(imageDataKey)
        body.appendString("\r\n")

        body.appendString("–\(boundary)–\r\n")

        return body
    }

    func generateBoundaryString() -> String {
        return "Boundary-\(NSUUID().UUIDString)"
    }

}
extension NSMutableData {
    func appendString(string: String) {
        let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
        appendData(data!)
    }
}

我有上传按钮并选择按钮。问题是,我实际上无法将图片上传到网站。我尝试了不同的方法来选择一个URL,我使用了服务器的目录,但没有一个工作......但话又说回来,我不知道PHP或swift非常好,我在一个教程的帮助下编写了这个项目。

0 个答案:

没有答案