Vernissage/PixelfedKit/Sources/PixelfedKit/Networking/MultipartFormData.swift

44 lines
1.3 KiB
Swift
Raw Normal View History

2023-01-20 16:57:25 +01:00
//
// https://mczachurski.dev
// Copyright © 2022 Marcin Czachurski and the repository contributors.
2023-03-28 10:35:38 +02:00
// Licensed under the Apache License 2.0.
2023-01-20 16:57:25 +01:00
//
2023-01-10 08:04:25 +01:00
import Foundation
2023-02-17 12:21:09 +01:00
struct MultipartFormData {
private let boundary: String
private var httpBody = NSMutableData()
2023-01-10 08:04:25 +01:00
2023-02-17 12:21:09 +01:00
private let separator: String = "\r\n"
2023-01-10 08:04:25 +01:00
2023-02-17 12:21:09 +01:00
init(boundary: String) {
self.boundary = boundary
}
2023-01-10 08:04:25 +01:00
2023-02-17 12:21:09 +01:00
func addTextField(named name: String, value: String) {
httpBody.append("--\(boundary)\(separator)")
httpBody.append(disposition(name) + separator)
httpBody.append("Content-Type: text/plain; charset=UTF-8" + separator + separator)
httpBody.append(value)
httpBody.append(separator)
2023-01-10 08:04:25 +01:00
}
2023-02-17 12:21:09 +01:00
func addDataField(named name: String, fileName: String, data: Data, mimeType: String) {
httpBody.append("--\(boundary)\(separator)")
httpBody.append(disposition(name) + "; filename=\"\(fileName)\"" + separator)
httpBody.append("Content-Type: \(mimeType)" + separator + separator)
httpBody.append(data)
httpBody.append(separator)
}
private func disposition(_ name: String) -> String {
"Content-Disposition: form-data; name=\"\(name)\""
}
func build() -> Data {
httpBody.append("--\(boundary)\(separator)")
return httpBody as Data
2023-01-10 08:04:25 +01:00
}
}