Skip to content

Instantly share code, notes, and snippets.

@michaelhenry
Last active November 19, 2018 15:22
Show Gist options
  • Save michaelhenry/4e34ed2a5ec650a64008505b0837814f to your computer and use it in GitHub Desktop.
Save michaelhenry/4e34ed2a5ec650a64008505b0837814f to your computer and use it in GitHub Desktop.
MultipartData model [limitation: supports 1 item only] Reference: https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2
import Foundation
class MultipartData {
let data:Data
let filename:String
let key:String
let mimeType:String
private let boundary:String
init(data:Data, key:String, filename:String, mimeType:String) {
self.data = data
self.key = key
self.filename = filename
self.mimeType = mimeType
self.boundary = "\(arc4random())"
}
private var contentType:String {
return "multipart/form-data; boundary=\(boundary)"
}
private lazy var dataValue:Data = {
let _data = NSMutableData()
_data.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
_data.append("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(filename)\"\r\n".data(using: String.Encoding.utf8)!)
_data.append("\r\n".data(using: String.Encoding.utf8)!)
_data.append(self.data)
_data.append("--\(boundary)--".data(using: String.Encoding.utf8)!)
return _data as Data
}()
private var contentLength:String {
return "\(dataValue.count)"
}
func asURLRequest(url:URL, httpMethod:String = "POST") -> URLRequest? {
let _request = NSMutableURLRequest(url: url)
_request.httpMethod = httpMethod
_request.httpBody = dataValue
_request.addValue(
contentType,
forHTTPHeaderField: "Content-Type")
_request.addValue(
"\(contentLength)",
forHTTPHeaderField: "Content-Length")
return _request as URLRequest
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment