CURL with Alamofire - Swift - multipart/form-data

NMA*_*427 3 curl multipartform-data swift alamofire swift2

首先,我很抱歉,如果这个问题是愚蠢的,但我对这个东西很新.我尝试过用Alamofire创建快速等效的cURL请求,但我不知道如何将图像作为multipart/form-data发送到API.

curl -X POST -F "file=@/Users/nicolas/sample.png" -F "mode=document_photo" https://api.idolondemand.com/1/api/sync/ocrdocument/v1 -F "apikey=xxx-xxx-xxx-xxx-xxx"
Run Code Online (Sandbox Code Playgroud)

我认为当前的代码对于这种类型的请求是非常错误的,但我仍然会为你发布它:

func getOCR(image: UIImage) {

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

    Alamofire.request(.POST, url, parameters: ["apikey": apiKey, "file": imageData!]).responseJSON() {
        _,_,JSON in
        print(JSON)
    }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止它对我有用的唯一方法是使用URL,但是因为我尝试将图像发送到用户用相机拍摄的服务器,所以我只能发送图像文件.

网址代码:

func test(url: NSURL) {

    let url = "https://api.idolondemand.com/1/api/sync/ocrdocument/v1"
    let apiKey = "xxx-xxx-xxx-xxx-xxx"

    Alamofire.request(.POST, url, parameters: ["apikey": apiKey, "url": url]).responseJSON() {
        _,JSON,_ in
        print(JSON)
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我收到回复,我会很高兴,因为这让我发疯.

PS.我正在使用swift 2.0

fqd*_*qdn 6

Alamofire都有自己的一个实例文档使用Alamofire.upload(_:URLString:headers:multipartFormData:encodingMemoryThreshold:encodingCompletion:),看起来像它会回答你的问题(注意,在他们的榜样,在headersencodingMemoryThreshold参数有一个默认值,如果你不提供一个).

另请参阅appendBodyPart()有关MultipartFormData类实例上的各种方法的文档.

因此,您提供的示例代码可以修改的方式可能是:

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)
      }
    }
  )
}
Run Code Online (Sandbox Code Playgroud)