gpt4 book ai didi

ios - 如何发送值为image、key为 'file'的图片文件

转载 作者:行者123 更新时间:2023-11-29 05:47:19 24 4
gpt4 key购买 nike

由于我是 iOS 新手,被困在这里一段时间了,我需要将图像上传到服务器,键和值为 ("file": image),在 postman 中找到附件中的图像。

我几乎尝试了这里的所有建议 How to upload images to a server in iOS with Swift? , Upload image to server - Swift 3

这里我尝试了一些东西,但由于请求中未传递 key 而没有得到输出响应

let url = URL(string: uploadurl);
let request = NSMutableURLRequest(url: url!);
request.httpMethod = "POST"
let boundary = "Boundary-\(NSUUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let imageData = UIImageJPEGRepresentation(image, 1)
if (imageData == nil) {
print("UIImageJPEGRepresentation return nil")
return
}
let body = NSMutableData()
//here I need to pass the data as ["file":image]
body.append(imageData!)
request.httpBody = body as Data
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if let data = data {
// do
let json = try!JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary
print("json value \(json)")
} else if let error = error {
print(error.localizedDescription)
}
})
task.resume()

请建议我如何将这些图像作为 ["file": image] 传递到正文中。

提前致谢

最佳答案

您可以使用URLSession上传multipart/form-data

  1. 上传

上传图片的功能

    // build request URL

guard let requestURL = URL(string: "YOURURL") else {
return
}

// prepare request
var request = URLRequest(url: requestURL)
request.allHTTPHeaderFields = header
request.httpMethod = MethodHttp.post.rawValue

let boundary = generateBoundaryString()

request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
// built data from img
if let imageData = image.jpegData(compressionQuality: 1) {
request.httpBody = createBodyWithParameters(parameters: param, filePathKey: "file", imageDataKey: imageData, boundary: boundary)
}

let task = URLSession.shared.dataTask(with: request,
completionHandler: { (data, _, error) -> Void in

if let data = data {

debugPrint("image uploaded successfully \(data)")

} else if let error = error {
debugPrint(error.localizedDescription)
}
})
task.resume()
  1. body

将创建请求正文的函数

 func createBodyWithParameters(parameters: [String: String],

filePathKey: String,
imageDataKey: Data,
boundary: String) -> Data {

let body = NSMutableData()
let mimetype = "image/*"

body.append("--\(boundary)\r\n".data(using: .utf8) ?? Data())
body.append("Content-Disposition: form-data; name=\"\(filePathKey)\"; filename=\"\(filePathKey)\"\r\n".data(using: .utf8) ?? Data())
body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: .utf8) ?? Data())
body.append(imageDataKey)
body.append("\r\n".data(using: .utf8) ?? Data())

body.append("--\(boundary)--\r\n".data(using: .utf8) ?? Data())



return body as Data
}

private func generateBoundaryString() -> String {
return "Boundary-\(Int.random(in: 1000 ... 9999))"
}

}
  • 数据扩展

    extension NSMutableData {

    func appendString(_ string: String) {
    if let data = string.data(using: String.Encoding.utf8,
    allowLossyConversion: true) {
    append(data)
    }
    }
    }
  • 关于ios - 如何发送值为image、key为 'file'的图片文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56016076/

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