2016-05-17 50 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