MultipartFormData.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. // MultipartFormData.swift
  2. //
  3. // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. import Foundation
  23. #if os(iOS)
  24. import MobileCoreServices
  25. #elseif os(OSX)
  26. import CoreServices
  27. #endif
  28. /**
  29. Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode
  30. multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead
  31. to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the
  32. data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for
  33. larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset.
  34. For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well
  35. and the w3 form documentation.
  36. - http://www.ietf.org/rfc/rfc2388.txt
  37. - http://www.ietf.org/rfc/rfc2045.txt
  38. - http://www.w3.org/TR/html401/interact/forms.html#h-17.13
  39. */
  40. public class MultipartFormData {
  41. // MARK: - Helper Types
  42. /**
  43. Used to specify whether encoding was successful.
  44. */
  45. public enum EncodingResult {
  46. case Success(NSData)
  47. case Failure(NSError)
  48. }
  49. struct EncodingCharacters {
  50. static let CRLF = "\r\n"
  51. }
  52. struct BoundaryGenerator {
  53. enum BoundaryType {
  54. case Initial, Encapsulated, Final
  55. }
  56. static func randomBoundary() -> String {
  57. return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random())
  58. }
  59. static func boundaryData(#boundaryType: BoundaryType, boundary: String) -> NSData {
  60. let boundaryText: String
  61. switch boundaryType {
  62. case .Initial:
  63. boundaryText = "--\(boundary)\(EncodingCharacters.CRLF)"
  64. case .Encapsulated:
  65. boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)\(EncodingCharacters.CRLF)"
  66. case .Final:
  67. boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)--\(EncodingCharacters.CRLF)"
  68. }
  69. return boundaryText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
  70. }
  71. }
  72. class BodyPart {
  73. let headers: [String: String]
  74. let bodyStream: NSInputStream
  75. let bodyContentLength: UInt64
  76. var hasInitialBoundary = false
  77. var hasFinalBoundary = false
  78. init(headers: [String: String], bodyStream: NSInputStream, bodyContentLength: UInt64) {
  79. self.headers = headers
  80. self.bodyStream = bodyStream
  81. self.bodyContentLength = bodyContentLength
  82. }
  83. }
  84. // MARK: - Properties
  85. /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`.
  86. public var contentType: String { return "multipart/form-data; boundary=\(self.boundary)" }
  87. /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries.
  88. public var contentLength: UInt64 { return self.bodyParts.reduce(0) { $0 + $1.bodyContentLength } }
  89. /// The boundary used to separate the body parts in the encoded form data.
  90. public let boundary: String
  91. private var bodyParts: [BodyPart]
  92. private let streamBufferSize: Int
  93. // MARK: - Lifecycle
  94. /**
  95. Creates a multipart form data object.
  96. :returns: The multipart form data object.
  97. */
  98. public init() {
  99. self.boundary = BoundaryGenerator.randomBoundary()
  100. self.bodyParts = []
  101. /**
  102. * The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
  103. * information, please refer to the following article:
  104. * - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html
  105. */
  106. self.streamBufferSize = 1024
  107. }
  108. // MARK: - Body Parts
  109. /**
  110. Creates a body part from the file and appends it to the multipart form data object.
  111. The body part data will be encoded using the following format:
  112. - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header)
  113. - `Content-Type: #{generated mimeType}` (HTTP Header)
  114. - Encoded file data
  115. - Multipart form boundary
  116. The filename in the `Content-Disposition` HTTP header is generated from the last path component of the
  117. `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the
  118. system associated MIME type.
  119. :param: URL The URL of the file whose content will be encoded into the multipart form data.
  120. :param: name The name to associate with the file content in the `Content-Disposition` HTTP header.
  121. :returns: An `NSError` if an error occurred, `nil` otherwise.
  122. */
  123. public func appendBodyPart(fileURL URL: NSURL, name: String) -> NSError? {
  124. let fileName: String
  125. let mimeType: String
  126. if let lastPathComponent = URL.lastPathComponent {
  127. fileName = lastPathComponent
  128. } else {
  129. let failureReason = "Failed to extract the fileName of the provided URL: \(URL)"
  130. let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
  131. return NSError(domain: AlamofireErrorDomain, code: NSURLErrorBadURL, userInfo: userInfo)
  132. }
  133. if let pathExtension = URL.pathExtension {
  134. mimeType = mimeTypeForPathExtension(pathExtension)
  135. } else {
  136. let failureReason = "Failed to extract the file extension of the provided URL: \(URL)"
  137. let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
  138. return NSError(domain: AlamofireErrorDomain, code: NSURLErrorBadURL, userInfo: userInfo)
  139. }
  140. return appendBodyPart(fileURL: URL, name: name, fileName: fileName, mimeType: mimeType)
  141. }
  142. /**
  143. Creates a body part from the file and appends it to the multipart form data object.
  144. The body part data will be encoded using the following format:
  145. - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
  146. - Content-Type: #{mimeType} (HTTP Header)
  147. - Encoded file data
  148. - Multipart form boundary
  149. :param: URL The URL of the file whose content will be encoded into the multipart form data.
  150. :param: name The name to associate with the file content in the `Content-Disposition` HTTP header.
  151. :param: fileName The filename to associate with the file content in the `Content-Disposition` HTTP header.
  152. :param: mimeType The MIME type to associate with the file content in the `Content-Type` HTTP header.
  153. :returns: An `NSError` if an error occurred, `nil` otherwise.
  154. */
  155. public func appendBodyPart(fileURL URL: NSURL, name: String, fileName: String, mimeType: String) -> NSError? {
  156. let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
  157. var reachableError: NSError?
  158. if !URL.fileURL {
  159. return errorWithCode(NSURLErrorBadURL, failureReason: "The URL does not point to a valid file: \(URL)")
  160. } else if !URL.checkResourceIsReachableAndReturnError(&reachableError) {
  161. return errorWithCode(NSURLErrorBadURL, failureReason: "The URL is not reachable: \(URL)")
  162. }
  163. let bodyContentLength: UInt64
  164. var fileAttributesError: NSError?
  165. if let
  166. path = URL.path,
  167. attributes = NSFileManager.defaultManager().attributesOfItemAtPath(path, error: &fileAttributesError),
  168. fileSize = (attributes[NSFileSize] as? NSNumber)?.unsignedLongLongValue
  169. {
  170. bodyContentLength = fileSize
  171. } else {
  172. return errorWithCode(NSURLErrorBadURL, failureReason: "Could not fetch attributes from the URL: \(URL)")
  173. }
  174. if let bodyStream = NSInputStream(URL: URL) {
  175. let bodyPart = BodyPart(headers: headers, bodyStream: bodyStream, bodyContentLength: bodyContentLength)
  176. self.bodyParts.append(bodyPart)
  177. } else {
  178. let failureReason = "Failed to create an input stream from the URL: \(URL)"
  179. return errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason)
  180. }
  181. return nil
  182. }
  183. /**
  184. Creates a body part from the data and appends it to the multipart form data object.
  185. The body part data will be encoded using the following format:
  186. - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
  187. - `Content-Type: #{mimeType}` (HTTP Header)
  188. - Encoded file data
  189. - Multipart form boundary
  190. :param: data The data to encode into the multipart form data.
  191. :param: name The name to associate with the data in the `Content-Disposition` HTTP header.
  192. :param: fileName The filename to associate with the data in the `Content-Disposition` HTTP header.
  193. :param: mimeType The MIME type to associate with the data in the `Content-Type` HTTP header.
  194. */
  195. public func appendBodyPart(fileData data: NSData, name: String, fileName: String, mimeType: String) {
  196. let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
  197. let bodyStream = NSInputStream(data: data)
  198. let bodyContentLength = UInt64(data.length)
  199. let bodyPart = BodyPart(headers: headers, bodyStream: bodyStream, bodyContentLength: bodyContentLength)
  200. self.bodyParts.append(bodyPart)
  201. }
  202. /**
  203. Creates a body part from the data and appends it to the multipart form data object.
  204. The body part data will be encoded using the following format:
  205. - `Content-Disposition: form-data; name=#{name}` (HTTP Header)
  206. - Encoded file data
  207. - Multipart form boundary
  208. :param: data The data to encode into the multipart form data.
  209. :param: name The name to associate with the data in the `Content-Disposition` HTTP header.
  210. */
  211. public func appendBodyPart(#data: NSData, name: String) {
  212. let headers = contentHeaders(name: name)
  213. let bodyStream = NSInputStream(data: data)
  214. let bodyContentLength = UInt64(data.length)
  215. let bodyPart = BodyPart(headers: headers, bodyStream: bodyStream, bodyContentLength: bodyContentLength)
  216. self.bodyParts.append(bodyPart)
  217. }
  218. /**
  219. Creates a body part from the stream and appends it to the multipart form data object.
  220. The body part data will be encoded using the following format:
  221. - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
  222. - `Content-Type: #{mimeType}` (HTTP Header)
  223. - Encoded file data
  224. - Multipart form boundary
  225. :param: stream The input stream to encode in the multipart form data.
  226. :param: name The name to associate with the stream content in the `Content-Disposition` HTTP header.
  227. :param: fileName The filename to associate with the stream content in the `Content-Disposition` HTTP header.
  228. :param: mimeType The MIME type to associate with the stream content in the `Content-Type` HTTP header.
  229. */
  230. public func appendBodyPart(#stream: NSInputStream, name: String, fileName: String, length: UInt64, mimeType: String) {
  231. let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
  232. let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length)
  233. self.bodyParts.append(bodyPart)
  234. }
  235. // MARK: - Data Extraction
  236. /**
  237. Encodes all the appended body parts into a single `NSData` object.
  238. It is important to note that this method will load all the appended body parts into memory all at the same
  239. time. This method should only be used when the encoded data will have a small memory footprint. For large data
  240. cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method.
  241. :returns: EncodingResult containing an `NSData` object if the encoding succeeded, an `NSError` otherwise.
  242. */
  243. public func encode() -> EncodingResult {
  244. var encoded = NSMutableData()
  245. self.bodyParts.first?.hasInitialBoundary = true
  246. self.bodyParts.last?.hasFinalBoundary = true
  247. for bodyPart in self.bodyParts {
  248. let encodedDataResult = encodeBodyPart(bodyPart)
  249. switch encodedDataResult {
  250. case .Failure:
  251. return encodedDataResult
  252. case let .Success(data):
  253. encoded.appendData(data)
  254. }
  255. }
  256. return .Success(encoded)
  257. }
  258. /**
  259. Writes the appended body parts into the given file URL asynchronously and calls the `completionHandler`
  260. when finished.
  261. This process is facilitated by reading and writing with input and output streams, respectively. Thus,
  262. this approach is very memory efficient and should be used for large body part data.
  263. :param: fileURL The file URL to write the multipart form data into.
  264. :param: completionHandler A closure to be executed when writing is finished.
  265. */
  266. public func writeEncodedDataToDisk(fileURL: NSURL, completionHandler: (NSError?) -> Void) {
  267. if !fileURL.fileURL {
  268. let failureReason = "The URL does not point to a valid file: \(fileURL)"
  269. let error = errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
  270. completionHandler(error)
  271. return
  272. }
  273. let outputStream: NSOutputStream
  274. if let possibleOutputStream = NSOutputStream(URL: fileURL, append: false) {
  275. outputStream = possibleOutputStream
  276. } else {
  277. let failureReason = "Failed to create an output stream with the given URL: \(fileURL)"
  278. let error = errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason)
  279. completionHandler(error)
  280. return
  281. }
  282. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
  283. outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  284. outputStream.open()
  285. self.bodyParts.first?.hasInitialBoundary = true
  286. self.bodyParts.last?.hasFinalBoundary = true
  287. var error: NSError?
  288. for bodyPart in self.bodyParts {
  289. if let writeError = self.writeBodyPart(bodyPart, toOutputStream: outputStream) {
  290. error = writeError
  291. break
  292. }
  293. }
  294. outputStream.close()
  295. outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  296. dispatch_async(dispatch_get_main_queue()) {
  297. completionHandler(error)
  298. }
  299. }
  300. }
  301. // MARK: - Private - Body Part Encoding
  302. private func encodeBodyPart(bodyPart: BodyPart) -> EncodingResult {
  303. let encoded = NSMutableData()
  304. let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
  305. encoded.appendData(initialData)
  306. let headerData = encodeHeaderDataForBodyPart(bodyPart)
  307. encoded.appendData(headerData)
  308. let bodyStreamResult = encodeBodyStreamDataForBodyPart(bodyPart)
  309. switch bodyStreamResult {
  310. case .Failure:
  311. return bodyStreamResult
  312. case let .Success(data):
  313. encoded.appendData(data)
  314. }
  315. if bodyPart.hasFinalBoundary {
  316. encoded.appendData(finalBoundaryData())
  317. }
  318. return .Success(encoded)
  319. }
  320. private func encodeHeaderDataForBodyPart(bodyPart: BodyPart) -> NSData {
  321. var headerText = ""
  322. for (key, value) in bodyPart.headers {
  323. headerText += "\(key): \(value)\(EncodingCharacters.CRLF)"
  324. }
  325. headerText += EncodingCharacters.CRLF
  326. return headerText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
  327. }
  328. private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) -> EncodingResult {
  329. let inputStream = bodyPart.bodyStream
  330. inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  331. inputStream.open()
  332. var error: NSError?
  333. let encoded = NSMutableData()
  334. while inputStream.hasBytesAvailable {
  335. var buffer = [UInt8](count: self.streamBufferSize, repeatedValue: 0)
  336. let bytesRead = inputStream.read(&buffer, maxLength: self.streamBufferSize)
  337. if inputStream.streamError != nil {
  338. error = inputStream.streamError
  339. break
  340. }
  341. if bytesRead < 0 {
  342. let failureReason = "Failed to read from input stream: \(inputStream)"
  343. error = errorWithCode(AlamofireInputStreamReadFailed, failureReason: failureReason)
  344. break
  345. }
  346. encoded.appendBytes(buffer, length: bytesRead)
  347. }
  348. inputStream.close()
  349. inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  350. if let error = error {
  351. return .Failure(error)
  352. }
  353. return .Success(encoded)
  354. }
  355. // MARK: - Private - Writing Body Part to Output Stream
  356. private func writeBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? {
  357. if let error = writeInitialBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) {
  358. return error
  359. }
  360. if let error = writeHeaderDataForBodyPart(bodyPart, toOutputStream: outputStream) {
  361. return error
  362. }
  363. if let error = writeBodyStreamForBodyPart(bodyPart, toOutputStream: outputStream) {
  364. return error
  365. }
  366. if let error = writeFinalBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) {
  367. return error
  368. }
  369. return nil
  370. }
  371. private func writeInitialBoundaryDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? {
  372. let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
  373. return writeData(initialData, toOutputStream: outputStream)
  374. }
  375. private func writeHeaderDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? {
  376. let headerData = encodeHeaderDataForBodyPart(bodyPart)
  377. return writeData(headerData, toOutputStream: outputStream)
  378. }
  379. private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? {
  380. var error: NSError?
  381. let inputStream = bodyPart.bodyStream
  382. inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  383. inputStream.open()
  384. while inputStream.hasBytesAvailable {
  385. var buffer = [UInt8](count: self.streamBufferSize, repeatedValue: 0)
  386. let bytesRead = inputStream.read(&buffer, maxLength: self.streamBufferSize)
  387. if inputStream.streamError != nil {
  388. error = inputStream.streamError
  389. break
  390. }
  391. if bytesRead < 0 {
  392. let failureReason = "Failed to read from input stream: \(inputStream)"
  393. error = errorWithCode(AlamofireInputStreamReadFailed, failureReason: failureReason)
  394. break
  395. }
  396. if buffer.count != bytesRead {
  397. buffer = Array(buffer[0..<bytesRead])
  398. }
  399. if let writeError = writeBuffer(&buffer, toOutputStream: outputStream) {
  400. error = writeError
  401. break
  402. }
  403. }
  404. inputStream.close()
  405. inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  406. return error
  407. }
  408. private func writeFinalBoundaryDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? {
  409. if bodyPart.hasFinalBoundary {
  410. return writeData(finalBoundaryData(), toOutputStream: outputStream)
  411. }
  412. return nil
  413. }
  414. // MARK: - Private - Writing Buffered Data to Output Stream
  415. private func writeData(data: NSData, toOutputStream outputStream: NSOutputStream) -> NSError? {
  416. var buffer = [UInt8](count: data.length, repeatedValue: 0)
  417. data.getBytes(&buffer, length: data.length)
  418. return writeBuffer(&buffer, toOutputStream: outputStream)
  419. }
  420. private func writeBuffer(inout buffer: [UInt8], toOutputStream outputStream: NSOutputStream) -> NSError? {
  421. var error: NSError?
  422. var bytesToWrite = buffer.count
  423. while bytesToWrite > 0 {
  424. if outputStream.hasSpaceAvailable {
  425. let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite)
  426. if outputStream.streamError != nil {
  427. error = outputStream.streamError
  428. break
  429. }
  430. if bytesWritten < 0 {
  431. let failureReason = "Failed to write to output stream: \(outputStream)"
  432. error = errorWithCode(AlamofireOutputStreamWriteFailed, failureReason: failureReason)
  433. break
  434. }
  435. bytesToWrite -= bytesWritten
  436. if bytesToWrite > 0 {
  437. buffer = Array(buffer[bytesWritten..<buffer.count])
  438. }
  439. } else if outputStream.streamError != nil {
  440. error = outputStream.streamError
  441. break
  442. }
  443. }
  444. return error
  445. }
  446. // MARK: - Private - Mime Type
  447. private func mimeTypeForPathExtension(pathExtension: String) -> String {
  448. let identifier = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil).takeRetainedValue()
  449. if let contentType = UTTypeCopyPreferredTagWithClass(identifier, kUTTagClassMIMEType) {
  450. return contentType.takeRetainedValue() as String
  451. }
  452. return "application/octet-stream"
  453. }
  454. // MARK: - Private - Content Headers
  455. private func contentHeaders(#name: String) -> [String: String] {
  456. return ["Content-Disposition": "form-data; name=\"\(name)\""]
  457. }
  458. private func contentHeaders(#name: String, fileName: String, mimeType: String) -> [String: String] {
  459. return [
  460. "Content-Disposition": "form-data; name=\"\(name)\"; filename=\"\(fileName)\"",
  461. "Content-Type": "\(mimeType)"
  462. ]
  463. }
  464. // MARK: - Private - Boundary Encoding
  465. private func initialBoundaryData() -> NSData {
  466. return BoundaryGenerator.boundaryData(boundaryType: .Initial, boundary: self.boundary)
  467. }
  468. private func encapsulatedBoundaryData() -> NSData {
  469. return BoundaryGenerator.boundaryData(boundaryType: .Encapsulated, boundary: self.boundary)
  470. }
  471. private func finalBoundaryData() -> NSData {
  472. return BoundaryGenerator.boundaryData(boundaryType: .Final, boundary: self.boundary)
  473. }
  474. // MARK: - Private - Errors
  475. private func errorWithCode(code: Int, failureReason: String) -> NSError {
  476. let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
  477. return NSError(domain: AlamofireErrorDomain, code: code, userInfo: userInfo)
  478. }
  479. }