通过HTTP $ _POST

时间:2016-05-17 04:37:54

标签: php swift http post

我使用此代码(Swift)将用户从其照片中选择的图像上传到服务器:

let imageFormatted = UIImageJPEGRepresentation(imageView.image!, 0.5);
    let uuid = NSUUID().UUIDString
    print ("MARK -- UUID is " + uuid)
    Alamofire.upload(
        .POST,
        "http://www.memer.onlie/upload.php",
        multipartFormData: { multipartFormData in
            multipartFormData.appendBodyPart(data: imageFormatted!, name: "imagefile",
                fileName: uuid + ".jpg", mimeType: "image/jpeg")
        },
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .Success(let upload, _, _):
                upload.validate()
                upload.responseJSON { response in
                    dispatch_async(dispatch_get_main_queue()) {
                        self.displayAlert("Uploaded!", message: "Your meme was uploaded, and you might see it in the app soon!", responseButtonText: "<3")
                    }
                    var json = JSON(data: response.data!)
                    print ("MARK -- JSON response: " + json["response"].stringValue)
                }
                print ("MARK -- Upload success!")
            case .Failure(let encodingError):
                print(encodingError)
                print ("MARK -- Upload failure!")
                self.displayAlert("Issue uploading.", message: "There was an issue uploading your meme.", responseButtonText: "Aww :(")
            }
        }
    )

没有图像上传到服务器。我能纠正什么才能让它发挥作用?

已编辑的代码。

1 个答案:

答案 0 :(得分:0)

thread可帮助您了解未考虑的内容以及解决问题所需执行的操作。我想你需要正确设置请求标题和正文部分。如果你使用Alamofire并且必须使用'multipart / form-data'编码类型,你可以编写这样的代码。

    Alamofire.upload(.POST, destURL, headers: yourHeader, multipartFormData: {    multipartFormData in

        if let imageData = UIImageJPEGRepresentation(image, 0.5) {
            multipartFormData.appendBodyPart(data: imageData, name:"file", fileName: "imagefile", mimeType: "image/jpg")
        }

        // Append parameters you should send  
        for (key, value) in parameters {
            multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
        }

        }, encodingCompletion: {  encodingResult in

            switch encodingResult {

            case .Success(let upload, _, _):
                upload.validate()
                upload.responseJSON { response in

                // do something if response is success
                }

            case .Failure(_):
                // do something if response is fail
            }
    })