swift-multipart-formdata

1.0.1

Build multipart/form-data type-safe in Swift.
FelixHerrmann/swift-multipart-formdata

What's New

1.0.1

2022-02-01T21:58:57Z

What's Changed

  • Add missing CRLF epilogue by @MMP0 in #2

New Contributors

  • @MMP0 made their first contribution in #2

Full Changelog: 1.0.0...1.0.1

MultipartFormData

Swift Version License Tweet

Build multipart/form-data type-safe in Swift. A result builder DSL is also available.

Installation

Swift Package Manager

Add the following to the dependencies of your Package.swift:

.package(url: "https://github.com/FelixHerrmann/swift-multipart-formdata.git", from: "x.x.x")

Xcode

Add the package to your project as shown here.

Manual

Download the files in the Sources folder and drag them into you project.

Usage

import MultipartFormData

let boundary = try Boundary(uncheckedBoundary: "example-boundary")
let multipartFormData = try MultipartFormData(boundary: boundary) {
    Subpart {
        ContentDisposition(name: "field1")
    } body: {
        Data("value1".utf8)
    }
    try Subpart {
        ContentDisposition(name: "field2")
        ContentType(mediaType: .applicationJson)
    } body: {
        try JSONSerialization.data(withJSONObject: ["string": "abcd", "int": 1234], options: .prettyPrinted)
    }
    
    let filename = "test.png"
    let homeDirectory = FileManager.default.homeDirectoryForCurrentUser
    let fileDirectory = homeDirectory.appendingPathComponent("Desktop").appendingPathComponent(filename)
    
    if FileManager.default.fileExists(atPath: fileDirectory.path) {
        try Subpart {
            try ContentDisposition(uncheckedName: "field3", uncheckedFilename: filename)
            ContentType(mediaType: .applicationOctetStream)
        } body: {
            try Data(contentsOf: fileDirectory)
        }
    }
}

let url = URL(string: "https://example.com/example")!
let request = URLRequest(url: url, multipartFormData: multipartFormData)
let (data, response) = try await URLSession.shared.data(for: request)
The generated HTTP request
POST https://example.com/example HTTP/1.1
Content-Length: 428
Content-Type: multipart/form-data; boundary="example-boundary"

--example-boundary
Content-Disposition: form-data; name="field1"

value1
--example-boundary
Content-Disposition: form-data; name="field2"
Content-Type: application/json

{
  "string" : "abcd",
  "int" : 1234
}
--example-boundary
Content-Disposition: form-data; name="field3"; filename="test.png"
Content-Type: application/octet-stream

<<png-data>>
--example-boundary--

For a detailed description read the code documentation.

License

MultipartFormData is available under the MIT license. See the LICENSE file for more info.

Description

  • Swift Tools 5.5.0
View More Packages from this Author

Dependencies

  • None
Last updated: Sun Jan 29 2023 16:23:07 GMT-0500 (GMT-05:00)