gpt4 book ai didi

ios - 如何在多部分http发布请求中发布图像数组

转载 作者:可可西里 更新时间:2023-11-01 01:57:52 27 4
gpt4 key购买 nike

我想上传图片数组,我应该如何将 array 添加到 NSMutableData 中。这是我的代码

func createBodyWithParametersMulti(parameters: [String: String]?, filePathKey: String?, imageDataKey: [NSData?], boundary: String) -> NSData {
let body = NSMutableData();

if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}

if(imageDataKey.count != 0){
let filename=filePathKey as! String
// let mimetype = "image/jpeg"

body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filename)\"; filename=\"image.jpg\"\r\n")
// body.appendString("Content-Disposition: form-data; name=\"image\"; filename=\"image.jpg\"\r\n")
body.appendString("Content-Type: \("image.jpeg")\r\n\r\n")


body.append(imageDataKey[0]! as Data)
body.appendString("\r\n")
}
else {

}
body.appendString("--\(boundary)--\r\n")

return body
}

ImageDataKey 是包含多个图像的 array 的名称作为 NSData

最佳答案

试试这个

func createBodyWithParametersAndImages(parameters: [String: Any]?, filePathKey: [String], imageDataKey: [Data], boundary: String) -> NSData {
let body = NSMutableData();

if parameters != nil {
for (key, value) in parameters! {
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString(string: "\(value)\r\n")
}
}

for index in 0..<imageDataKey.count {
let data = imageDataKey[index]

let filename = "image.jpeg"
let mimetype = "image/jpeg"

body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(filePathKey[index])\"; filename=\"\(filename)\"\r\n")
body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
body.append(data)
body.appendString(string: "\r\n")

}


body.appendString(string: "--\(boundary)--\r\n")

return body
}

方法调用

let body = createBodyWithParametersAndImages(parameters: parameter, filePathKey: ["profile_image", "cover_image"], imageDataKey: [imageData1, ImageData2] as! [NSData], boundary: boundary) as Data
request.httpBody = body

关于ios - 如何在多部分http发布请求中发布图像数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49853961/

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