gpt4 book ai didi

swift - cURL 与 Alamofire - Swift - 多部分/表单数据

转载 作者:搜寻专家 更新时间:2023-10-31 22:07:42 25 4
gpt4 key购买 nike

首先,如果这个问题很愚蠢,我很抱歉,但我对这个东西还很陌生。我尝试了不同的方法来创建与 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"

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

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

到目前为止,它对我唯一有效的方法是使用 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)
}
}

如果我得到回应我会很高兴,因为这让我发疯。

附言。我正在使用 swift 2.0

最佳答案

Alamofire 在他们的 documentation 中有一个例子使用 Alamofire.upload(_:URLString:headers:multipartFormData:encodingMemoryThreshold:encodingCompletion:) 看起来会回答您的问题(请注意,在他们的示例中,headersencodingMemoryThreshold 如果您不提供参数,则参数具有默认值)。

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

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

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

关于swift - cURL 与 Alamofire - Swift - 多部分/表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31834704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com