0

I don't know php and swift well so can you help me? I have a server: cs.hisarschool.k12.tr/ecs.php and this is the code:

<?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"]
    ]);
}

?>

The swift code:

//
//  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!)
    }
}

I have the upload button and select button. The problem is, I can't actually upload a picture to the website. I tried different ways of selecting an URL, i used the directory of the server but none works... But then again, I don't know PHP or swift very well, I wrote this project with the help of a tutorial.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Mert Karakas
  • 178
  • 1
  • 4
  • 22
  • check this link http://stackoverflow.com/questions/26162616/upload-image-with-parameters-in-swift – Shruti May 15 '15 at 12:15
  • @Shruti I think i looked at every post about this in stackoverflow but none worked for me. – Mert Karakas May 15 '15 at 12:17
  • are you sure you are providing the correct key – Shruti May 15 '15 at 12:25
  • Are you getting anything on the server/php side ? More debug statements might clarify things a bit. I'm betting your client code is the culprit here, have you considered using AFNetworking https://github.com/AFNetworking/AFNetworking ? At the very least it could let you isolate the problem somehow – smaura777 May 15 '15 at 12:30
  • {"Message":"Sorry, there was an error uploading your file().","Status":"Error","userId":null} is the error message – Mert Karakas May 15 '15 at 12:41
  • @Shruti What key are you talking about? – Mert Karakas May 15 '15 at 12:42
  • Try using [https://github.com/AFNetworking/AFNetworking] instead of the base URLRequest – user623396 May 15 '15 at 12:45
  • The fieldName is whatever field name your server code is looking for when identifying the uploads. For example, if your server code was written in PHP, this is whatever field name the server code uses in its $_FILES references. – Shruti May 15 '15 at 12:46
  • See i got this.... check i think here your keywords are ["file"]["tmp_name"] try to use these only as name while uploading – Shruti May 15 '15 at 12:47
  • @Shruti Is the swift code correct then? I should only change php code? – Mert Karakas May 15 '15 at 17:14
  • @user623396 the link you gave doesn't exist – Mert Karakas May 15 '15 at 17:14
  • @MertKarakas https://github.com/AFNetworking/AFNetworking Einstein! – user623396 May 15 '15 at 19:35

0 Answers0