2016-05-17 73 views
0

我使用這個代碼(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 :(") 
      } 
     } 
    ) 

沒有圖片被上傳到服務器。我能糾正什麼才能使這個工作?

已編輯的代碼。

回答

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 
      } 
    }) 
+0

我正在使用這個,查看編輯後的代碼,但它沒有發送到服務器,也沒有響應。 @woogii –

+0

難道你沒有任何HTTP頭或額外的參數?你從答覆中得到的錯誤是什麼?你可以參考這個[線程](http://stackoverflow.com/questions/26121827/uploading-file-with-parameters-using-alamofire/26747857#26747857)它顯示了關於Alamorfire上傳請求的各種示例代碼。 – woogii