我想上传图片数组,我应该如何将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
的{{1}}的名称。
答案 0 :(得分:1)
试一下
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