gpt4 book ai didi

ios - 在 SWIFT 中将图像作为 POST 发送

转载 作者:行者123 更新时间:2023-11-28 07:30:14 25 4
gpt4 key购买 nike

我正在尝试将 UIImage 发布到 API 以从该 UIImage 读取文本,但出现以下错误:另外,如何在控制台上打印 urlRequest 以查看其中的元素。我也尝试过 Alamofire,但问题似乎是请求未正确发送。非常感谢任何类型的帮助。

Error: 
AsSynchronous{
error = {
code = 400;
message = "Wrong request: No file sent in the request, please set the field 'files'";
requestId = "d9adb89b-cd67-48e4-7846-0aa4c78fc08e";
};
}

我的代码是:

`func uploadImage(paramName: String, fileName: String, image: UIImage,apiKey:String) {

let boundary = UUID().uuidString


let urlRequest = NSMutableURLRequest(url: NSURL(string: "https://xxxxxxxxxxxxx")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
urlRequest.httpMethod = "POST"


urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

let headers = [
"content-type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
"apikey": "yyyyyyyyyyyyyyyyy",
"cache-control": "no-cache",
"Postman-Token": "87b45036-1107-4db6-bf4d-7dc83314045b"
]
urlRequest.allHTTPHeaderFields = headers
var data = Data()
var value = "files"
// Add the userhash field and its value to the raw http reqyest data
data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
data.append("Content-Disposition: form-data; name=\"\(paramName)\"\r\n\r\n".data(using: .utf8)!)
data.append("\(value)".data(using: .utf8)!)

// Add the image data to the raw http request data
data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
data.append("Content-Disposition: form-data; name=\"image\"; filename=\"\(fileName)\"\r\n".data(using: .utf8)!)
data.append("Content-Type: image/jpeg\r\n\r\n".data(using: .utf8)!)
data.append(UIImageJPEGRepresentation(image, 0.1)!)


data.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)

urlRequest.httpBody = data


print("value of data is", data)

//NSString requestReply = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//print("requestReply: %@%@", requestReply);

let session = URLSession.shared
let dataTask = session.dataTask(with: urlRequest as URLRequest, completionHandler: { (data, response, error) -> Void in
if let _data = data
{
do {
var jsonResult: NSDictionary
try jsonResult = JSONSerialization.jsonObject(with: _data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
print("AsSynchronous\(jsonResult)")
}
catch {
// handle error
}
}
else
{
print("Error: no data for request \(urlRequest)")
}
/* if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print("got any response")
print(NSString(data: data!, encoding: String.Encoding.utf8.rawValue))
print("may be")

print(httpResponse)

}*/
})

dataTask.resume()
}`

最佳答案

您将图像文件中的 Data 和表单主体的 Data 放在一起。

class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}

@IBAction func postTapped(_ sender: UIButton) {
postData()
}

func postData() {
let image = UIImage(imageLiteralResourceName: "myImage.jpg")
guard let imageData = UIImageJPEGRepresentation(image) else {
print("oops")
return
}
let url = URL(string: "http://www.example.net/example.php")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.timeoutInterval = 30.0

let uuid = UUID().uuidString
let CRLF = "\r\n"
let filename = uuid + ".jpg"
let formName = "file"
let type = "image/jpeg" // file type
let boundary = String(format: "----iOSURLSessionBoundary.%08x%08x", arc4random(), arc4random())
var body = Data()

// file data //
body.append(("--\(boundary)" + CRLF).data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"formName\"; filename=\"\(fileName)\"\r\n".data(using: .utf8)!)
body.append(("Content-Type: \(type)" + CRLF + CRLF).data(using: .utf8)!)
body.append(imageData as Data)
body.append(CRLF.data(using: .utf8)!)

// footer //
body.append(("--\(boundary)--" + CRLF).data(using: .utf8)!)
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

request.httpBody = body
let session = URLSession(configuration: .default)
session.dataTask(with: request) { (data, response, error) in
...
...
}
}

关于ios - 在 SWIFT 中将图像作为 POST 发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55013763/

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