MultipartFormDataKit

master

Simple library for multipart/form-data for Swift.
Kuniwak/MultipartFormDataKit

MultipartFormDataKit

Swift 5.6 compatible Swift Package Manager and Carthage and CocoaPods compatible v2.0.0 Build Status

multipart/form-data for Swift.

Basic Usage

let multipartFormData = try MultipartFormData.Builder.build(
    with: [
        (
            name: "example1",
            filename: nil,
            mimeType: nil,
            data: "Hello, World!".data(using: .utf8)!
        ),
        (
            name: "example2",
            filename: "example.txt",
            mimeType: MIMEType.textPlain,
            data: "EXAMPLE_TXT".data(using: .utf8)!
        ),
    ],
    willSeparateBy: RandomBoundaryGenerator.generate()
)

var request = URLRequest(url: URL(string: "http://example.com")!)
request.httpMethod = "POST"
request.setValue(multipartFormData.contentType, forHTTPHeaderField: "Content-Type")
request.httpBody = multipartFormData.body

let task = URLSession.shared.dataTask(with: request)
task.resume()

Advanced Usage

let multipartFormData = MultipartFormData(
    uniqueAndValidLengthBoundary: "boundary",
    body: [
        MultipartFormData.Part(
            contentDisposition: ContentDisposition(
                name: Name(asPercentEncoded: "field%201"),
                filename: nil
            ),
            contentType: nil,
            content: "value1".data(using: .utf8)!
        ),
        MultipartFormData.Part(
            contentDisposition: ContentDisposition(
                name: Name(asPercentEncoded: "field%202"),
                filename: Filename(asPercentEncoded: "example.txt")
            ),
            contentType: ContentType(representing: .textPlain),
            content: "value2".data(using: .utf8)!
        ),
    ]
)

print(multipartFormData.header.name)
// Content-Type

print(multipartFormData.header.value)
// multipart/form-data; boundary="boundary"

switch multipartFormData.asData() {
case let .valid(data):
    print(String(data: data, encoding: .utf8))

    // --boundary
    // Content-Disposition: form-data; name="field1"
    // 
    // value1
    // --boundary
    // Content-Disposition: form-data; name="filed2"; filename="example.txt"
    // Content-Type: text/plain
    // 
    // value2
    // --boundary--

case let .invalid(error):
    print(error)
}

License

MIT

Description

  • Swift Tools 5.6.0
View More Packages from this Author

Dependencies

  • None
Last updated: Fri Oct 18 2024 06:57:48 GMT-0900 (Hawaii-Aleutian Daylight Time)