title: Swift Alamofire upload image in variable for rails API
body: <p>So here is my problem, I must upload an image in my swift application to a server that use rails. I got almost everything set up, except that the rails api must receive the file data in a variable document[:file]</p>
  
  <p>here is the function I use to encode my image with alamofire:</p>
  
  <pre><code>static func getDocumentCreateUploadData(parameters: [String : AnyObject], imageData: NSData) -&gt; (uploadData:NSMutableData, contentType:String) {
      let boundaryConstant = "NET-POST-boundary-\(arc4random())-\(arc4random())";
      let contentType = "multipart/form-data;boundary="+boundaryConstant
  
      let uploadData = NSMutableData()
  
      // add image
      uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
      uploadData.appendData("Content-Disposition: form-data; name=\"file\"; filename=\"file.png\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
      uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
      uploadData.appendData(imageData)
  
      // add parameters
      for (key, value) in parameters {
          uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
          uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
      }
      uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
  
      return (uploadData, contentType)
  }
  </code></pre>
  
  <p>And then I call my api with</p>
  
  <pre><code>var imageParameters = [
       "documents": [
            "documentable_type": "Profile",
            "documentable_id": user.profile.id!
       ]
  ]
  let data = Router.getDocumentCreateUploadData(imageParameters, imageData: imageData)
  let urlRequest = Router.CreateDocument(contentType: data.contentType)
  Alamofire.upload(urlRequest, data.uploadData).validate().responseSwiftyJSON({ (request, response, json, error) in
      if error != nil {
         ...
  </code></pre>
  
  <p>What I would like to know is how can I encode the image so that it respect the api specification.</p>
  
  <pre><code>{
      "documents" : {
          "file": the_file,
          "documentable_type": the_documentable_type,
          "documentable_id": the_documentable_id
      }
  }
  </code></pre>
  
  <p>Is there a way to achieve this?</p>
  
  <p>Thank in advance.</p>