cURL with Alamofire - Swift - multipart/form-data

感情迁移 提交于 2019-12-03 17:25:57

Alamofire has an example in their documentation using Alamofire.upload(_:URLString:headers:multipartFormData:encodingMemoryThreshold:encodingCompletion:) that looks like it will answer your question (note that in their example, the headers and encodingMemoryThreshold parameters have a default value if you don't supply one).

Also see their documentation on the various appendBodyPart() methods on a MultipartFormData class instance.

So, a way in which your provided example code could be modified might be:

func getOCR(image: UIImage) {

  let url = "https://api.idolondemand.com/1/api/sync/ocrdocument/v1"
  let apiKey = "xxx-xxx-xxx-xxx-xxx"
  let mode = "document_photo"
  let imageData = UIImagePNGRepresentation(image)

  Alamofire.upload(
    .POST,
    URLString: url,
    multipartFormData: { multipartFormData in
      multipartFormData.appendBodyPart(
        data: apiKey.dataUsingEncoding(NSUTF8StringEncoding)!,
        name: "apikey"
      )
      multipartFormData.appendBodyPart(
        data: mode.dataUsingEncoding(NSUTF8StringEncoding)!,
        name: "mode"
      )
      multipartFormData.appendBodyPart(
        data: imageData!,
        name: "file",
        fileName: "testIMG.png",
        mimeType: "image/png"
      )
    },
    encodingCompletion: { encodingResult in
      switch encodingResult {
        case .Success(let upload, _, _):
          upload.responseJSON { _, _, JSON in println(JSON) }
        case .Failure(let encodingError):
          println(encodingError)
      }
    }
  )
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!