我需要在单个api调用中将一个图像和一个pdf文件以及一些参数上传到服务器。我不知道如何为此创建主体。我知道为单个数据创建一个正文,但不知道为两个数据创建一个正文。您能告诉我createBodyWithParameter以及如何为两个数据分配文件名和Mimetype。
func createBodyWithParameters(parameters: [String: Any]?, ImagePathKey: String?, imageDataKey: NSData,FilePathKey: String?, fileDatakey: NSData, 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")
}
}
let filename = ".png"
let mimetype = "image/jpg"
let filenames = ".pdf"
let mimetypes = "application/pdf"
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(ImagePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(FilePathKey!)\"; filename=\"\(filenames)\"\r\n")
body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
body.appendString(string: "Content-Type: \(mimetypes)\r\n\r\n")
body.append(imageDataKey as Data)
body.append(fileDatakey as Data)
body.appendString(string: "\r\n")
body.appendString(string: "--\(boundary)--\r\n")
return body
}`
let parameter = ["UserId":1,"Name":userNameOrEamilTF.text!,"PhoneCode":countryCodeTF.text!,"Phone":phone,"DisplayPreference":displayReference,"region":region] as [String : Any]
这是我创建的正文并在此处分配数据和键以及imagedata,filedata具有数据
request.httpBody = createBodyWithParameters(parameters: param, filePathKey: "profile", imageDataKey: imageData! as NSData,FilePathKey: "Resume", fileDatakey: filedata as NSData, boundary: boundary) as Data