簡體   English   中英

通過HTTP $ _POST上傳Swift圖像

[英]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
            }
    })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM