我有向正文添加值的代码:
let body = NSMutableData()
let mimetype = "image/jpg"
//define the data post parameter
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition:form-data; name=\"eventId\"\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append("\(eventId)\r\n".data(using: String.Encoding.utf8)!)
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition:form-data; name=\"contactId\"\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append("\(contactId)\r\n".data(using: String.Encoding.utf8)!)
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition:form-data; name=\"type\"\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append("\(type)\r\n".data(using: String.Encoding.utf8)!)
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition:form-data; name=\"file\"; filename=\"\(fileName)\"\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append(image_data!)
body.append("\r\n".data(using: String.Encoding.utf8)!)
body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
request.httpBody = body as Data
如何将其转换为字符串?我想获得界限,但不可能做到。
[当我这样做时,它使我为零:let test = String(data: body as Data, encoding: .utf8)
非常感谢。
如果需要边界,则应在与图像数据不同的对象中创建其页眉和页脚数据:
var body = Data()
let boundary = UUID().uuidString
let eventId = "your event ID"
let contactId = "your contact ID"
let type = "your type string"
let mimetype = "image/jpg"
let fileName = "the file name"
let imageData = Data() // your image data
let boundaryHeader = Data("""
--\(boundary)\r\n
Content-Disposition:form-data; name=\"eventId\"\r\n\r\n
\(eventId)\r\n
--\(boundary)\r\n
Content-Disposition:form-data; name=\"contactId\"\r\n\r\n
\(contactId)\r\n
--\(boundary)\r\n
Content-Disposition:form-data; name=\"type\"\r\n\r\n
\(type)\r\n
--\(boundary)\r\n
Content-Disposition:form-data; name=\"file\"; filename=\"\(fileName)\"\r\n
Content-Type: \(mimetype)\r\n\r\n
""".utf8)
let boundaryFooter = Data("""
\r\n
--\(boundary)--\r\n
""".utf8)
body.append(boundaryHeader)
body.append(imageData)
body.append(boundaryFooter)
var request = URLRequest(url: URL(string: "http://www.example.com/whatever")!)
request.httpBody = body
print(String(data: boundaryHeader, encoding: .utf8) ?? "nil")
这将打印:
Content-Disposition:form-data; name =“ contactId”
您的联系人ID
-2583374D-68AF-4EE1-96A5-740CCA17C51D
Content-Disposition:form-data; name =“ type”
您的类型字符串
-2583374D-68AF-4EE1-96A5-740CCA17C51D
Content-Disposition:form-data; name =“文件”; filename =“文件名”
内容类型:图像/ jpg