drd0833 2016-07-23 22:11 采纳率: 100%
浏览 97

通过php上传图片swift到服务器

I followed a tutorial online to upload image to server from swift. I used his sample interface and everything looks fine except I'm getting error "Message":"Sorry, there was an error uploading your file.","Status":Error,"userId":"9". My codes are

<?php
    $firstName = $_POST["firstName"];
    $lastName = $_POST["lastName"];
    $userId = $_POST["userId"];

    $target_dir = "percyteng.com/orbit/ios/image";if(!file_exists($target_dir))
    {
    mkdir($target_dir, 0777, true);
    }

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

    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",
    "userId" => $_REQUEST["userId"]
    ]);
    } else {

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

    }
    ?>

I have checked and the parameters did get passed from swift. Here is my code in swift.

    import UIKit

    class ViewController: UIViewController, UIPickerViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate{


    @IBOutlet weak var image: UIImageView!
    @IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!

      override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.view.endEditing(true)
    }

    @IBAction func selectImage(sender: AnyObject) {
        let ImagePicker = UIImagePickerController()
        ImagePicker.delegate = self
        ImagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary

        self.presentViewController(ImagePicker, animated: true, completion: nil)
    }
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

        image.image = info[UIImagePickerControllerOriginalImage] as? UIImage
        self.dismissViewControllerAnimated(true, completion: nil)

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

    }

    @IBAction func Upload(sender: AnyObject) {
        myImageUploadRequest()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func myImageUploadRequest()
    {

        let myUrl = NSURL(string: "http://www.percyteng.com/orbit/ios/try.php");
        //let myUrl = NSURL(string: "http://www.boredwear.com/utils/postImage.php");

        let request = NSMutableURLRequest(URL:myUrl!);
        request.HTTPMethod = "POST";

        let param = [
            "firstName"  : "Sergey",
            "lastName"    : "Kargopolov",
            "userId"    : "9"
        ]

        let boundary = generateBoundaryString()

        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")


        let imageData = UIImageJPEGRepresentation(image.image!, 1)

        if(imageData==nil)  { return; }

        request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData!, boundary: boundary)



        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in

            if error != nil {
                print("error=\(error)")
                return
            }

            // You can print out response object
            print("******* response = \(response)")

            // Print out reponse body
            let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("****** response data = \(responseString!)")

            do {
                if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                    print(jsonResult)
                }
            } catch let error as NSError {
                print(error.localizedDescription)
            }


            dispatch_async(dispatch_get_main_queue(),{
//                self.myActivityIndicator.stopAnimating()
                self.image.image = nil;
            });

            /*
             if let parseJSON = json {
             var firstNameValue = parseJSON["firstName"] as? String
             println("firstNameValue: \(firstNameValue)")
             }
             */

        }

        task.resume()

    }


    func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
        var body = NSMutableData();

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

")
                body.appendString("\(value)
")
            }
        }

        let filename = "user-profile.jpg"

        let mimetype = "image/jpg"

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

")
        body.appendData(imageDataKey)
        body.appendString("
")



        body.appendString("--\(boundary)--
")

        return body
    }




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



    }


    extension NSMutableData {

    func appendString(string: String) {
        let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
        appendData(data!)
    }
    }
  • 写回答

1条回答 默认 最新

  • dsfsda121545 2016-08-01 17:56
    关注

    Your iOS code works for me if I use move_uploaded_file() in the php script to move the image from the tempfile path to an existing dir on my server, so that I don't run into problems creating the dir (I also commented out the json conversion of the response). Therefore, the boundaries in the body of the request were all created correctly.

    I suspect move_uploaded_file() is failing because of a directory problem. Try something like this:

    if(!file_exists($target_dir))
    {
        mkdir($target_dir, 0777, true) or exit("Couldn't create $target_dir!");
    
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?