MultipartFormData.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. // MultipartFormData.swift
  2. //
  3. // Copyright (c) 2014–2016 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) || os(watchOS) || os(tvOS)
  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. - https://www.ietf.org/rfc/rfc2388.txt
  37. - https://www.ietf.org/rfc/rfc2045.txt
  38. - https://www.w3.org/TR/html401/interact/forms.html#h-17.13
  39. */
  40. public class MultipartFormData {
  41. // MARK: - Helper Types
  42. struct EncodingCharacters {
  43. static let CRLF = "\r\n"
  44. }
  45. struct BoundaryGenerator {
  46. enum BoundaryType {
  47. case Initial, Encapsulated, Final
  48. }
  49. static func randomBoundary() -> String {
  50. return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random())
  51. }
  52. static func boundaryData(boundaryType boundaryType: BoundaryType, boundary: String) -> NSData {
  53. let boundaryText: String
  54. switch boundaryType {
  55. case .Initial:
  56. boundaryText = "--\(boundary)\(EncodingCharacters.CRLF)"
  57. case .Encapsulated:
  58. boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)\(EncodingCharacters.CRLF)"
  59. case .Final:
  60. boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)--\(EncodingCharacters.CRLF)"
  61. }
  62. return boundaryText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
  63. }
  64. }
  65. class BodyPart {
  66. let headers: [String: String]
  67. let bodyStream: NSInputStream
  68. let bodyContentLength: UInt64
  69. var hasInitialBoundary = false
  70. var hasFinalBoundary = false
  71. init(headers: [String: String], bodyStream: NSInputStream, bodyContentLength: UInt64) {
  72. self.headers = headers
  73. self.bodyStream = bodyStream
  74. self.bodyContentLength = bodyContentLength
  75. }
  76. }
  77. // MARK: - Properties
  78. /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`.
  79. public var contentType: String { return "multipart/form-data; boundary=\(boundary)" }
  80. /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries.
  81. public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } }
  82. /// The boundary used to separate the body parts in the encoded form data.
  83. public let boundary: String
  84. private var bodyParts: [BodyPart]
  85. private var bodyPartError: NSError?
  86. private let streamBufferSize: Int
  87. // MARK: - Lifecycle
  88. /**
  89. Creates a multipart form data object.
  90. - returns: The multipart form data object.
  91. */
  92. public init() {
  93. self.boundary = BoundaryGenerator.randomBoundary()
  94. self.bodyParts = []
  95. /**
  96. * The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
  97. * information, please refer to the following article:
  98. * - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html
  99. */
  100. self.streamBufferSize = 1024
  101. }
  102. // MARK: - Body Parts
  103. /**
  104. Creates a body part from the data and appends it to the multipart form data object.
  105. The body part data will be encoded using the following format:
  106. - `Content-Disposition: form-data; name=#{name}` (HTTP Header)
  107. - Encoded data
  108. - Multipart form boundary
  109. - parameter data: The data to encode into the multipart form data.
  110. - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
  111. */
  112. public func appendBodyPart(data data: NSData, name: String) {
  113. let headers = contentHeaders(name: name)
  114. let stream = NSInputStream(data: data)
  115. let length = UInt64(data.length)
  116. appendBodyPart(stream: stream, length: length, headers: headers)
  117. }
  118. /**
  119. Creates a body part from the data and appends it to the multipart form data object.
  120. The body part data will be encoded using the following format:
  121. - `Content-Disposition: form-data; name=#{name}` (HTTP Header)
  122. - `Content-Type: #{generated mimeType}` (HTTP Header)
  123. - Encoded data
  124. - Multipart form boundary
  125. - parameter data: The data to encode into the multipart form data.
  126. - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
  127. - parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header.
  128. */
  129. public func appendBodyPart(data data: NSData, name: String, mimeType: String) {
  130. let headers = contentHeaders(name: name, mimeType: mimeType)
  131. let stream = NSInputStream(data: data)
  132. let length = UInt64(data.length)
  133. appendBodyPart(stream: stream, length: length, headers: headers)
  134. }
  135. /**
  136. Creates a body part from the data and appends it to the multipart form data object.
  137. The body part data will be encoded using the following format:
  138. - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
  139. - `Content-Type: #{mimeType}` (HTTP Header)
  140. - Encoded file data
  141. - Multipart form boundary
  142. - parameter data: The data to encode into the multipart form data.
  143. - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
  144. - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header.
  145. - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header.
  146. */
  147. public func appendBodyPart(data data: NSData, name: String, fileName: String, mimeType: String) {
  148. let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
  149. let stream = NSInputStream(data: data)
  150. let length = UInt64(data.length)
  151. appendBodyPart(stream: stream, length: length, headers: headers)
  152. }
  153. /**
  154. Creates a body part from the file and appends it to the multipart form data object.
  155. The body part data will be encoded using the following format:
  156. - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header)
  157. - `Content-Type: #{generated mimeType}` (HTTP Header)
  158. - Encoded file data
  159. - Multipart form boundary
  160. The filename in the `Content-Disposition` HTTP header is generated from the last path component of the
  161. `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the
  162. system associated MIME type.
  163. - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
  164. - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
  165. */
  166. public func appendBodyPart(fileURL fileURL: NSURL, name: String) {
  167. if let
  168. fileName = fileURL.lastPathComponent,
  169. pathExtension = fileURL.pathExtension
  170. {
  171. let mimeType = mimeTypeForPathExtension(pathExtension)
  172. appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType)
  173. } else {
  174. let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)"
  175. setBodyPartError(Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason))
  176. }
  177. }
  178. /**
  179. Creates a body part from the file and appends it to the multipart form data object.
  180. The body part data will be encoded using the following format:
  181. - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
  182. - Content-Type: #{mimeType} (HTTP Header)
  183. - Encoded file data
  184. - Multipart form boundary
  185. - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
  186. - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
  187. - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header.
  188. - parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header.
  189. */
  190. public func appendBodyPart(fileURL fileURL: NSURL, name: String, fileName: String, mimeType: String) {
  191. let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
  192. //============================================================
  193. // Check 1 - is file URL?
  194. //============================================================
  195. guard fileURL.fileURL else {
  196. let failureReason = "The file URL does not point to a file URL: \(fileURL)"
  197. let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
  198. setBodyPartError(error)
  199. return
  200. }
  201. //============================================================
  202. // Check 2 - is file URL reachable?
  203. //============================================================
  204. var isReachable = true
  205. if #available(OSX 10.10, *) {
  206. isReachable = fileURL.checkPromisedItemIsReachableAndReturnError(nil)
  207. }
  208. guard isReachable else {
  209. let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)")
  210. setBodyPartError(error)
  211. return
  212. }
  213. //============================================================
  214. // Check 3 - is file URL a directory?
  215. //============================================================
  216. var isDirectory: ObjCBool = false
  217. guard let
  218. path = fileURL.path
  219. where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else
  220. {
  221. let failureReason = "The file URL is a directory, not a file: \(fileURL)"
  222. let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
  223. setBodyPartError(error)
  224. return
  225. }
  226. //============================================================
  227. // Check 4 - can the file size be extracted?
  228. //============================================================
  229. var bodyContentLength: UInt64?
  230. do {
  231. if let
  232. path = fileURL.path,
  233. fileSize = try NSFileManager.defaultManager().attributesOfItemAtPath(path)[NSFileSize] as? NSNumber
  234. {
  235. bodyContentLength = fileSize.unsignedLongLongValue
  236. }
  237. } catch {
  238. // No-op
  239. }
  240. guard let length = bodyContentLength else {
  241. let failureReason = "Could not fetch attributes from the file URL: \(fileURL)"
  242. let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
  243. setBodyPartError(error)
  244. return
  245. }
  246. //============================================================
  247. // Check 5 - can a stream be created from file URL?
  248. //============================================================
  249. guard let stream = NSInputStream(URL: fileURL) else {
  250. let failureReason = "Failed to create an input stream from the file URL: \(fileURL)"
  251. let error = Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason)
  252. setBodyPartError(error)
  253. return
  254. }
  255. appendBodyPart(stream: stream, length: length, headers: headers)
  256. }
  257. /**
  258. Creates a body part from the stream and appends it to the multipart form data object.
  259. The body part data will be encoded using the following format:
  260. - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
  261. - `Content-Type: #{mimeType}` (HTTP Header)
  262. - Encoded stream data
  263. - Multipart form boundary
  264. - parameter stream: The input stream to encode in the multipart form data.
  265. - parameter length: The content length of the stream.
  266. - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header.
  267. - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header.
  268. - parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header.
  269. */
  270. public func appendBodyPart(
  271. stream stream: NSInputStream,
  272. length: UInt64,
  273. name: String,
  274. fileName: String,
  275. mimeType: String)
  276. {
  277. let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
  278. appendBodyPart(stream: stream, length: length, headers: headers)
  279. }
  280. /**
  281. Creates a body part with the headers, stream and length and appends it to the multipart form data object.
  282. The body part data will be encoded using the following format:
  283. - HTTP headers
  284. - Encoded stream data
  285. - Multipart form boundary
  286. - parameter stream: The input stream to encode in the multipart form data.
  287. - parameter length: The content length of the stream.
  288. - parameter headers: The HTTP headers for the body part.
  289. */
  290. public func appendBodyPart(stream stream: NSInputStream, length: UInt64, headers: [String: String]) {
  291. let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length)
  292. bodyParts.append(bodyPart)
  293. }
  294. // MARK: - Data Encoding
  295. /**
  296. Encodes all the appended body parts into a single `NSData` object.
  297. It is important to note that this method will load all the appended body parts into memory all at the same
  298. time. This method should only be used when the encoded data will have a small memory footprint. For large data
  299. cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method.
  300. - throws: An `NSError` if encoding encounters an error.
  301. - returns: The encoded `NSData` if encoding is successful.
  302. */
  303. public func encode() throws -> NSData {
  304. if let bodyPartError = bodyPartError {
  305. throw bodyPartError
  306. }
  307. let encoded = NSMutableData()
  308. bodyParts.first?.hasInitialBoundary = true
  309. bodyParts.last?.hasFinalBoundary = true
  310. for bodyPart in bodyParts {
  311. let encodedData = try encodeBodyPart(bodyPart)
  312. encoded.appendData(encodedData)
  313. }
  314. return encoded
  315. }
  316. /**
  317. Writes the appended body parts into the given file URL.
  318. This process is facilitated by reading and writing with input and output streams, respectively. Thus,
  319. this approach is very memory efficient and should be used for large body part data.
  320. - parameter fileURL: The file URL to write the multipart form data into.
  321. - throws: An `NSError` if encoding encounters an error.
  322. */
  323. public func writeEncodedDataToDisk(fileURL: NSURL) throws {
  324. if let bodyPartError = bodyPartError {
  325. throw bodyPartError
  326. }
  327. if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) {
  328. let failureReason = "A file already exists at the given file URL: \(fileURL)"
  329. throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
  330. } else if !fileURL.fileURL {
  331. let failureReason = "The URL does not point to a valid file: \(fileURL)"
  332. throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
  333. }
  334. let outputStream: NSOutputStream
  335. if let possibleOutputStream = NSOutputStream(URL: fileURL, append: false) {
  336. outputStream = possibleOutputStream
  337. } else {
  338. let failureReason = "Failed to create an output stream with the given URL: \(fileURL)"
  339. throw Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason)
  340. }
  341. outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  342. outputStream.open()
  343. self.bodyParts.first?.hasInitialBoundary = true
  344. self.bodyParts.last?.hasFinalBoundary = true
  345. for bodyPart in self.bodyParts {
  346. try writeBodyPart(bodyPart, toOutputStream: outputStream)
  347. }
  348. outputStream.close()
  349. outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  350. }
  351. // MARK: - Private - Body Part Encoding
  352. private func encodeBodyPart(bodyPart: BodyPart) throws -> NSData {
  353. let encoded = NSMutableData()
  354. let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
  355. encoded.appendData(initialData)
  356. let headerData = encodeHeaderDataForBodyPart(bodyPart)
  357. encoded.appendData(headerData)
  358. let bodyStreamData = try encodeBodyStreamDataForBodyPart(bodyPart)
  359. encoded.appendData(bodyStreamData)
  360. if bodyPart.hasFinalBoundary {
  361. encoded.appendData(finalBoundaryData())
  362. }
  363. return encoded
  364. }
  365. private func encodeHeaderDataForBodyPart(bodyPart: BodyPart) -> NSData {
  366. var headerText = ""
  367. for (key, value) in bodyPart.headers {
  368. headerText += "\(key): \(value)\(EncodingCharacters.CRLF)"
  369. }
  370. headerText += EncodingCharacters.CRLF
  371. return headerText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
  372. }
  373. private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData {
  374. let inputStream = bodyPart.bodyStream
  375. inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  376. inputStream.open()
  377. var error: NSError?
  378. let encoded = NSMutableData()
  379. while inputStream.hasBytesAvailable {
  380. var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0)
  381. let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
  382. if inputStream.streamError != nil {
  383. error = inputStream.streamError
  384. break
  385. }
  386. if bytesRead > 0 {
  387. encoded.appendBytes(buffer, length: bytesRead)
  388. } else if bytesRead < 0 {
  389. let failureReason = "Failed to read from input stream: \(inputStream)"
  390. error = Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason)
  391. break
  392. } else {
  393. break
  394. }
  395. }
  396. inputStream.close()
  397. inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  398. if let error = error {
  399. throw error
  400. }
  401. return encoded
  402. }
  403. // MARK: - Private - Writing Body Part to Output Stream
  404. private func writeBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
  405. try writeInitialBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream)
  406. try writeHeaderDataForBodyPart(bodyPart, toOutputStream: outputStream)
  407. try writeBodyStreamForBodyPart(bodyPart, toOutputStream: outputStream)
  408. try writeFinalBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream)
  409. }
  410. private func writeInitialBoundaryDataForBodyPart(
  411. bodyPart: BodyPart,
  412. toOutputStream outputStream: NSOutputStream)
  413. throws
  414. {
  415. let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
  416. return try writeData(initialData, toOutputStream: outputStream)
  417. }
  418. private func writeHeaderDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
  419. let headerData = encodeHeaderDataForBodyPart(bodyPart)
  420. return try writeData(headerData, toOutputStream: outputStream)
  421. }
  422. private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
  423. let inputStream = bodyPart.bodyStream
  424. inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  425. inputStream.open()
  426. while inputStream.hasBytesAvailable {
  427. var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0)
  428. let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
  429. if let streamError = inputStream.streamError {
  430. throw streamError
  431. }
  432. if bytesRead > 0 {
  433. if buffer.count != bytesRead {
  434. buffer = Array(buffer[0..<bytesRead])
  435. }
  436. try writeBuffer(&buffer, toOutputStream: outputStream)
  437. } else if bytesRead < 0 {
  438. let failureReason = "Failed to read from input stream: \(inputStream)"
  439. throw Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason)
  440. } else {
  441. break
  442. }
  443. }
  444. inputStream.close()
  445. inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  446. }
  447. private func writeFinalBoundaryDataForBodyPart(
  448. bodyPart: BodyPart,
  449. toOutputStream outputStream: NSOutputStream)
  450. throws
  451. {
  452. if bodyPart.hasFinalBoundary {
  453. return try writeData(finalBoundaryData(), toOutputStream: outputStream)
  454. }
  455. }
  456. // MARK: - Private - Writing Buffered Data to Output Stream
  457. private func writeData(data: NSData, toOutputStream outputStream: NSOutputStream) throws {
  458. var buffer = [UInt8](count: data.length, repeatedValue: 0)
  459. data.getBytes(&buffer, length: data.length)
  460. return try writeBuffer(&buffer, toOutputStream: outputStream)
  461. }
  462. private func writeBuffer(inout buffer: [UInt8], toOutputStream outputStream: NSOutputStream) throws {
  463. var bytesToWrite = buffer.count
  464. while bytesToWrite > 0 {
  465. if outputStream.hasSpaceAvailable {
  466. let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite)
  467. if let streamError = outputStream.streamError {
  468. throw streamError
  469. }
  470. if bytesWritten < 0 {
  471. let failureReason = "Failed to write to output stream: \(outputStream)"
  472. throw Error.errorWithCode(.OutputStreamWriteFailed, failureReason: failureReason)
  473. }
  474. bytesToWrite -= bytesWritten
  475. if bytesToWrite > 0 {
  476. buffer = Array(buffer[bytesWritten..<buffer.count])
  477. }
  478. } else if let streamError = outputStream.streamError {
  479. throw streamError
  480. }
  481. }
  482. }
  483. // MARK: - Private - Mime Type
  484. private func mimeTypeForPathExtension(pathExtension: String) -> String {
  485. if let
  486. id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue(),
  487. contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue()
  488. {
  489. return contentType as String
  490. }
  491. return "application/octet-stream"
  492. }
  493. // MARK: - Private - Content Headers
  494. private func contentHeaders(name name: String) -> [String: String] {
  495. return ["Content-Disposition": "form-data; name=\"\(name)\""]
  496. }
  497. private func contentHeaders(name name: String, mimeType: String) -> [String: String] {
  498. return [
  499. "Content-Disposition": "form-data; name=\"\(name)\"",
  500. "Content-Type": "\(mimeType)"
  501. ]
  502. }
  503. private func contentHeaders(name name: String, fileName: String, mimeType: String) -> [String: String] {
  504. return [
  505. "Content-Disposition": "form-data; name=\"\(name)\"; filename=\"\(fileName)\"",
  506. "Content-Type": "\(mimeType)"
  507. ]
  508. }
  509. // MARK: - Private - Boundary Encoding
  510. private func initialBoundaryData() -> NSData {
  511. return BoundaryGenerator.boundaryData(boundaryType: .Initial, boundary: boundary)
  512. }
  513. private func encapsulatedBoundaryData() -> NSData {
  514. return BoundaryGenerator.boundaryData(boundaryType: .Encapsulated, boundary: boundary)
  515. }
  516. private func finalBoundaryData() -> NSData {
  517. return BoundaryGenerator.boundaryData(boundaryType: .Final, boundary: boundary)
  518. }
  519. // MARK: - Private - Errors
  520. private func setBodyPartError(error: NSError) {
  521. if bodyPartError == nil {
  522. bodyPartError = error
  523. }
  524. }
  525. }