Swift图片通过HTTP$_POST上传


Swift Image upload via 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 :(")
            }
        }
    )

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

已编辑代码。

这个线程可以帮助您了解您没有考虑的内容以及需要做些什么来解决问题。我想您需要正确设置请求标头和正文部分。如果您使用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
            }
    })