MultipartFormData.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. //
  2. // MultipartFormData.swift
  3. //
  4. // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. #if canImport(MobileCoreServices)
  26. import MobileCoreServices
  27. #elseif canImport(CoreServices)
  28. import CoreServices
  29. #endif
  30. /// Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode
  31. /// multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead
  32. /// to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the
  33. /// data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for
  34. /// larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset.
  35. ///
  36. /// For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well
  37. /// and the w3 form documentation.
  38. ///
  39. /// - https://www.ietf.org/rfc/rfc2388.txt
  40. /// - https://www.ietf.org/rfc/rfc2045.txt
  41. /// - https://www.w3.org/TR/html401/interact/forms.html#h-17.13
  42. open class MultipartFormData {
  43. // MARK: - Helper Types
  44. enum EncodingCharacters {
  45. static let crlf = "\r\n"
  46. }
  47. enum BoundaryGenerator {
  48. enum BoundaryType {
  49. case initial, encapsulated, final
  50. }
  51. static func randomBoundary() -> String {
  52. let first = UInt32.random(in: UInt32.min...UInt32.max)
  53. let second = UInt32.random(in: UInt32.min...UInt32.max)
  54. return String(format: "alamofire.boundary.%08x%08x", first, second)
  55. }
  56. static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data {
  57. let boundaryText = switch boundaryType {
  58. case .initial:
  59. "--\(boundary)\(EncodingCharacters.crlf)"
  60. case .encapsulated:
  61. "\(EncodingCharacters.crlf)--\(boundary)\(EncodingCharacters.crlf)"
  62. case .final:
  63. "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)"
  64. }
  65. return Data(boundaryText.utf8)
  66. }
  67. }
  68. class BodyPart {
  69. let headers: HTTPHeaders
  70. let bodyStream: InputStream
  71. let bodyContentLength: UInt64
  72. var hasInitialBoundary = false
  73. var hasFinalBoundary = false
  74. init(headers: HTTPHeaders, bodyStream: InputStream, bodyContentLength: UInt64) {
  75. self.headers = headers
  76. self.bodyStream = bodyStream
  77. self.bodyContentLength = bodyContentLength
  78. }
  79. }
  80. // MARK: - Properties
  81. /// Default memory threshold used when encoding `MultipartFormData`, in bytes.
  82. public static let encodingMemoryThreshold: UInt64 = 10_000_000
  83. /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`.
  84. open lazy var contentType: String = "multipart/form-data; boundary=\(self.boundary)"
  85. /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries.
  86. public var contentLength: UInt64 { bodyParts.reduce(0) { $0 + $1.bodyContentLength } }
  87. /// The boundary used to separate the body parts in the encoded form data.
  88. public let boundary: String
  89. let fileManager: FileManager
  90. private var bodyParts: [BodyPart]
  91. private var bodyPartError: AFError?
  92. private let streamBufferSize: Int
  93. // MARK: - Lifecycle
  94. /// Creates an instance.
  95. ///
  96. /// - Parameters:
  97. /// - fileManager: `FileManager` to use for file operations, if needed.
  98. /// - boundary: Boundary `String` used to separate body parts.
  99. public init(fileManager: FileManager = .default, boundary: String? = nil) {
  100. self.fileManager = fileManager
  101. self.boundary = boundary ?? BoundaryGenerator.randomBoundary()
  102. bodyParts = []
  103. //
  104. // The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
  105. // information, please refer to the following article:
  106. // - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html
  107. //
  108. streamBufferSize = 1024
  109. }
  110. // MARK: - Body Parts
  111. /// Creates a body part from the data and appends it to the instance.
  112. ///
  113. /// The body part data will be encoded using the following format:
  114. ///
  115. /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
  116. /// - `Content-Type: #{mimeType}` (HTTP Header)
  117. /// - Encoded file data
  118. /// - Multipart form boundary
  119. ///
  120. /// - Parameters:
  121. /// - data: `Data` to encoding into the instance.
  122. /// - name: Name to associate with the `Data` in the `Content-Disposition` HTTP header.
  123. /// - fileName: Filename to associate with the `Data` in the `Content-Disposition` HTTP header.
  124. /// - mimeType: MIME type to associate with the data in the `Content-Type` HTTP header.
  125. public func append(_ data: Data, withName name: String, fileName: String? = nil, mimeType: String? = nil) {
  126. let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType)
  127. let stream = InputStream(data: data)
  128. let length = UInt64(data.count)
  129. append(stream, withLength: length, headers: headers)
  130. }
  131. /// Creates a body part from the file and appends it to the instance.
  132. ///
  133. /// The body part data will be encoded using the following format:
  134. ///
  135. /// - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header)
  136. /// - `Content-Type: #{generated mimeType}` (HTTP Header)
  137. /// - Encoded file data
  138. /// - Multipart form boundary
  139. ///
  140. /// The filename in the `Content-Disposition` HTTP header is generated from the last path component of the
  141. /// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the
  142. /// system associated MIME type.
  143. ///
  144. /// - Parameters:
  145. /// - fileURL: `URL` of the file whose content will be encoded into the instance.
  146. /// - name: Name to associate with the file content in the `Content-Disposition` HTTP header.
  147. public func append(_ fileURL: URL, withName name: String) {
  148. let fileName = fileURL.lastPathComponent
  149. let pathExtension = fileURL.pathExtension
  150. if !fileName.isEmpty && !pathExtension.isEmpty {
  151. let mime = mimeType(forPathExtension: pathExtension)
  152. append(fileURL, withName: name, fileName: fileName, mimeType: mime)
  153. } else {
  154. setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL))
  155. }
  156. }
  157. /// Creates a body part from the file and appends it to the instance.
  158. ///
  159. /// The body part data will be encoded using the following format:
  160. ///
  161. /// - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
  162. /// - Content-Type: #{mimeType} (HTTP Header)
  163. /// - Encoded file data
  164. /// - Multipart form boundary
  165. ///
  166. /// - Parameters:
  167. /// - fileURL: `URL` of the file whose content will be encoded into the instance.
  168. /// - name: Name to associate with the file content in the `Content-Disposition` HTTP header.
  169. /// - fileName: Filename to associate with the file content in the `Content-Disposition` HTTP header.
  170. /// - mimeType: MIME type to associate with the file content in the `Content-Type` HTTP header.
  171. public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) {
  172. let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType)
  173. //============================================================
  174. // Check 1 - is file URL?
  175. //============================================================
  176. guard fileURL.isFileURL else {
  177. setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL))
  178. return
  179. }
  180. //============================================================
  181. // Check 2 - is file URL reachable?
  182. //============================================================
  183. #if !(os(Linux) || os(Windows) || os(Android))
  184. do {
  185. let isReachable = try fileURL.checkPromisedItemIsReachable()
  186. guard isReachable else {
  187. setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL))
  188. return
  189. }
  190. } catch {
  191. setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error))
  192. return
  193. }
  194. #endif
  195. //============================================================
  196. // Check 3 - is file URL a directory?
  197. //============================================================
  198. var isDirectory: ObjCBool = false
  199. let path = fileURL.path
  200. guard fileManager.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else {
  201. setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL))
  202. return
  203. }
  204. //============================================================
  205. // Check 4 - can the file size be extracted?
  206. //============================================================
  207. let bodyContentLength: UInt64
  208. do {
  209. guard let fileSize = try fileManager.attributesOfItem(atPath: path)[.size] as? NSNumber else {
  210. setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL))
  211. return
  212. }
  213. bodyContentLength = fileSize.uint64Value
  214. } catch {
  215. setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error))
  216. return
  217. }
  218. //============================================================
  219. // Check 5 - can a stream be created from file URL?
  220. //============================================================
  221. guard let stream = InputStream(url: fileURL) else {
  222. setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL))
  223. return
  224. }
  225. append(stream, withLength: bodyContentLength, headers: headers)
  226. }
  227. /// Creates a body part from the stream and appends it to the instance.
  228. ///
  229. /// The body part data will be encoded using the following format:
  230. ///
  231. /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
  232. /// - `Content-Type: #{mimeType}` (HTTP Header)
  233. /// - Encoded stream data
  234. /// - Multipart form boundary
  235. ///
  236. /// - Parameters:
  237. /// - stream: `InputStream` to encode into the instance.
  238. /// - length: Length, in bytes, of the stream.
  239. /// - name: Name to associate with the stream content in the `Content-Disposition` HTTP header.
  240. /// - fileName: Filename to associate with the stream content in the `Content-Disposition` HTTP header.
  241. /// - mimeType: MIME type to associate with the stream content in the `Content-Type` HTTP header.
  242. public func append(_ stream: InputStream,
  243. withLength length: UInt64,
  244. name: String,
  245. fileName: String,
  246. mimeType: String) {
  247. let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType)
  248. append(stream, withLength: length, headers: headers)
  249. }
  250. /// Creates a body part with the stream, length, and headers and appends it to the instance.
  251. ///
  252. /// The body part data will be encoded using the following format:
  253. ///
  254. /// - HTTP headers
  255. /// - Encoded stream data
  256. /// - Multipart form boundary
  257. ///
  258. /// - Parameters:
  259. /// - stream: `InputStream` to encode into the instance.
  260. /// - length: Length, in bytes, of the stream.
  261. /// - headers: `HTTPHeaders` for the body part.
  262. public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) {
  263. let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length)
  264. bodyParts.append(bodyPart)
  265. }
  266. // MARK: - Data Encoding
  267. /// Encodes all appended body parts into a single `Data` value.
  268. ///
  269. /// - Note: This method will load all the appended body parts into memory all at the same time. This method should
  270. /// only be used when the encoded data will have a small memory footprint. For large data cases, please use
  271. /// the `writeEncodedData(to:))` method.
  272. ///
  273. /// - Returns: The encoded `Data`, if encoding is successful.
  274. /// - Throws: An `AFError` if encoding encounters an error.
  275. public func encode() throws -> Data {
  276. if let bodyPartError {
  277. throw bodyPartError
  278. }
  279. var encoded = Data()
  280. bodyParts.first?.hasInitialBoundary = true
  281. bodyParts.last?.hasFinalBoundary = true
  282. for bodyPart in bodyParts {
  283. let encodedData = try encode(bodyPart)
  284. encoded.append(encodedData)
  285. }
  286. return encoded
  287. }
  288. /// Writes all appended body parts to the given file `URL`.
  289. ///
  290. /// This process is facilitated by reading and writing with input and output streams, respectively. Thus,
  291. /// this approach is very memory efficient and should be used for large body part data.
  292. ///
  293. /// - Parameter fileURL: File `URL` to which to write the form data.
  294. /// - Throws: An `AFError` if encoding encounters an error.
  295. public func writeEncodedData(to fileURL: URL) throws {
  296. if let bodyPartError {
  297. throw bodyPartError
  298. }
  299. if fileManager.fileExists(atPath: fileURL.path) {
  300. throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL))
  301. } else if !fileURL.isFileURL {
  302. throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL))
  303. }
  304. guard let outputStream = OutputStream(url: fileURL, append: false) else {
  305. throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL))
  306. }
  307. outputStream.open()
  308. defer { outputStream.close() }
  309. bodyParts.first?.hasInitialBoundary = true
  310. bodyParts.last?.hasFinalBoundary = true
  311. for bodyPart in bodyParts {
  312. try write(bodyPart, to: outputStream)
  313. }
  314. }
  315. // MARK: - Private - Body Part Encoding
  316. private func encode(_ bodyPart: BodyPart) throws -> Data {
  317. var encoded = Data()
  318. let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
  319. encoded.append(initialData)
  320. let headerData = encodeHeaders(for: bodyPart)
  321. encoded.append(headerData)
  322. let bodyStreamData = try encodeBodyStream(for: bodyPart)
  323. encoded.append(bodyStreamData)
  324. if bodyPart.hasFinalBoundary {
  325. encoded.append(finalBoundaryData())
  326. }
  327. return encoded
  328. }
  329. private func encodeHeaders(for bodyPart: BodyPart) -> Data {
  330. let headerText = bodyPart.headers.map { "\($0.name): \($0.value)\(EncodingCharacters.crlf)" }
  331. .joined()
  332. + EncodingCharacters.crlf
  333. return Data(headerText.utf8)
  334. }
  335. private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data {
  336. let inputStream = bodyPart.bodyStream
  337. inputStream.open()
  338. defer { inputStream.close() }
  339. var encoded = Data()
  340. while inputStream.hasBytesAvailable {
  341. var buffer = [UInt8](repeating: 0, count: streamBufferSize)
  342. let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
  343. if let error = inputStream.streamError {
  344. throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error))
  345. }
  346. if bytesRead > 0 {
  347. encoded.append(buffer, count: bytesRead)
  348. } else {
  349. break
  350. }
  351. }
  352. guard UInt64(encoded.count) == bodyPart.bodyContentLength else {
  353. let error = AFError.UnexpectedInputStreamLength(bytesExpected: bodyPart.bodyContentLength,
  354. bytesRead: UInt64(encoded.count))
  355. throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error))
  356. }
  357. return encoded
  358. }
  359. // MARK: - Private - Writing Body Part to Output Stream
  360. private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws {
  361. try writeInitialBoundaryData(for: bodyPart, to: outputStream)
  362. try writeHeaderData(for: bodyPart, to: outputStream)
  363. try writeBodyStream(for: bodyPart, to: outputStream)
  364. try writeFinalBoundaryData(for: bodyPart, to: outputStream)
  365. }
  366. private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
  367. let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
  368. return try write(initialData, to: outputStream)
  369. }
  370. private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
  371. let headerData = encodeHeaders(for: bodyPart)
  372. return try write(headerData, to: outputStream)
  373. }
  374. private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
  375. let inputStream = bodyPart.bodyStream
  376. inputStream.open()
  377. defer { inputStream.close() }
  378. var bytesLeftToRead = bodyPart.bodyContentLength
  379. while inputStream.hasBytesAvailable && bytesLeftToRead > 0 {
  380. let bufferSize = min(streamBufferSize, Int(bytesLeftToRead))
  381. var buffer = [UInt8](repeating: 0, count: bufferSize)
  382. let bytesRead = inputStream.read(&buffer, maxLength: bufferSize)
  383. if let streamError = inputStream.streamError {
  384. throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError))
  385. }
  386. if bytesRead > 0 {
  387. if buffer.count != bytesRead {
  388. buffer = Array(buffer[0..<bytesRead])
  389. }
  390. try write(&buffer, to: outputStream)
  391. bytesLeftToRead -= UInt64(bytesRead)
  392. } else {
  393. break
  394. }
  395. }
  396. }
  397. private func writeFinalBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
  398. if bodyPart.hasFinalBoundary {
  399. try write(finalBoundaryData(), to: outputStream)
  400. }
  401. }
  402. // MARK: - Private - Writing Buffered Data to Output Stream
  403. private func write(_ data: Data, to outputStream: OutputStream) throws {
  404. var buffer = [UInt8](repeating: 0, count: data.count)
  405. data.copyBytes(to: &buffer, count: data.count)
  406. return try write(&buffer, to: outputStream)
  407. }
  408. private func write(_ buffer: inout [UInt8], to outputStream: OutputStream) throws {
  409. var bytesToWrite = buffer.count
  410. while bytesToWrite > 0, outputStream.hasSpaceAvailable {
  411. let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite)
  412. if let error = outputStream.streamError {
  413. throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error))
  414. }
  415. bytesToWrite -= bytesWritten
  416. if bytesToWrite > 0 {
  417. buffer = Array(buffer[bytesWritten..<buffer.count])
  418. }
  419. }
  420. }
  421. // MARK: - Private - Content Headers
  422. private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> HTTPHeaders {
  423. var disposition = "form-data; name=\"\(name)\""
  424. if let fileName { disposition += "; filename=\"\(fileName)\"" }
  425. var headers: HTTPHeaders = [.contentDisposition(disposition)]
  426. if let mimeType { headers.add(.contentType(mimeType)) }
  427. return headers
  428. }
  429. // MARK: - Private - Boundary Encoding
  430. private func initialBoundaryData() -> Data {
  431. BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary)
  432. }
  433. private func encapsulatedBoundaryData() -> Data {
  434. BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary)
  435. }
  436. private func finalBoundaryData() -> Data {
  437. BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary)
  438. }
  439. // MARK: - Private - Errors
  440. private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) {
  441. guard bodyPartError == nil else { return }
  442. bodyPartError = AFError.multipartEncodingFailed(reason: reason)
  443. }
  444. }
  445. #if canImport(UniformTypeIdentifiers)
  446. import UniformTypeIdentifiers
  447. extension MultipartFormData {
  448. // MARK: - Private - Mime Type
  449. private func mimeType(forPathExtension pathExtension: String) -> String {
  450. if #available(iOS 14, macOS 11, tvOS 14, watchOS 7, visionOS 1, *) {
  451. return UTType(filenameExtension: pathExtension)?.preferredMIMEType ?? "application/octet-stream"
  452. } else {
  453. if
  454. let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(),
  455. let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() {
  456. return contentType as String
  457. }
  458. return "application/octet-stream"
  459. }
  460. }
  461. }
  462. #else
  463. extension MultipartFormData {
  464. // MARK: - Private - Mime Type
  465. private func mimeType(forPathExtension pathExtension: String) -> String {
  466. #if canImport(CoreServices) || canImport(MobileCoreServices)
  467. if
  468. let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(),
  469. let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() {
  470. return contentType as String
  471. }
  472. #endif
  473. return "application/octet-stream"
  474. }
  475. }
  476. #endif