Alamofire源码解析 - MultipartFormData

Alamofire做过上传功能的应该都知道MutltipartFormData这个东西,可能大家使用的时候没有注意,只知道在一个闭包中调用append方法就可以了。大概就是这样

  Alamofire.upload(multipartFormData: { (MultipartFormData) in
                MultipartFormData.append(data, withName: "name", 
fileName:"xxx",mimeType: "application/octet-stream")
            } , to:"www.sss.xxx", 
encodingCompletion: { (EncodingResult) in
                ///
            })

append可以多次调用,每次append都会添加一个上传的内容,然后一起完成上传。在AFNetWorking中也存在AFMultipartFormData是一个协议

其实multipart/form-data的请求体也是一个字符串,不过和post的请求体不同的是它的结构,post是简单的name=value值连接,而multipart/form-data则是添加了分隔符和内容的结构。我也不是很懂网络方面的知识这是我自己理解的,想了解清楚的可以自行百度下。

  • AlamofireMultipartFormData中的作用就是,把需要上传的内容根据multipart/form-data的格式生成一个Data

Boundary

boundary就是分隔符的意思。MultipartFormData中有三种分隔符,initialencapsulatedfinal分别表示开始,内部,结束。

    struct EncodingCharacters {
        static let crlf = "\r\n"
    }

    struct BoundaryGenerator {
        enum BoundaryType {
            case initial, encapsulated, final
        }

        static func randomBoundary() -> String {
            return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random())
        }

        static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data {
            let boundaryText: String

            switch boundaryType {
            case .initial:
                boundaryText = "--\(boundary)\(EncodingCharacters.crlf)"
            case .encapsulated:
                boundaryText = "\(EncodingCharacters.crlf)--\(boundary)\(EncodingCharacters.crlf)"
            case .final:
                boundaryText = "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)"
            }

            return boundaryText.data(using: String.Encoding.utf8, allowLossyConversion: false)!
        }
    }

配合文件最后面的三个方法就可以生成三种分隔符,等会的代码中会用到三种分隔符。

    // MARK: - Private - Boundary Encoding

    private func initialBoundaryData() -> Data {
        return BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary)
    }

    private func encapsulatedBoundaryData() -> Data {
        return BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary)
    }

    private func finalBoundaryData() -> Data {
        return BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary)
    }


BodyPart

每次调用MultipartFormData的append方法,就是生成一个BodyPart然后存储在MultipartFormData的BodyParts数组中。

    class BodyPart {
        let headers: HTTPHeaders
        let bodyStream: InputStream
        let bodyContentLength: UInt64
        var hasInitialBoundary = false
        var hasFinalBoundary = false

        init(headers: HTTPHeaders, bodyStream: InputStream, bodyContentLength: UInt64) {
            self.headers = headers
            self.bodyStream = bodyStream
            self.bodyContentLength = bodyContentLength
        }
    }

MultipartFormData

MultipartFormData的属性


    /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`.
    open var contentType: String { return "multipart/form-data; boundary=\(boundary)" }

    /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries.
    public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } }

    /// The boundary used to separate the body parts in the encoded form data.
    public let boundary: String

    private var bodyParts: [BodyPart]
    private var bodyPartError: AFError?
    private let streamBufferSize: Int
  • contentType:multipart/form-data的请求头必须包含一个特殊的头信息Content-Type,且其值也必须规定为multipart/form-data,同时还需要规定一个内容分割符用于分割请求体中的多个内容,不然接收方就无法正常还原了。

  • contentLength:内容长度

  • boundary:分隔符

  • bodyParts:上传内容数组

-bodyPartError:错误信息

  • streamBufferSize: 流Buffer的大小

append 方法

append方法有很多但都会调用同一个append方法,把参数传化成bodyPart,然后添加进数组。

    public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) {
        let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length)
        bodyParts.append(bodyPart)
    }

encode 方法

encode方法就是根据格式把bodyParts转化成Data类型,在开始和内容间,以及结尾处都插入分隔符。MultipartFormData提供了两个方法,一个是适用于小文件的情况,另一个在文件较大的时候先把data写入文件在使用fileURL上传文件。由于调用的方法都是相同的,这里就只看了encode()方法

    public func encode() throws -> Data {
        if let bodyPartError = bodyPartError {
            throw bodyPartError
        }

        var encoded = Data()

        bodyParts.first?.hasInitialBoundary = true
        bodyParts.last?.hasFinalBoundary = true

        for bodyPart in bodyParts {
            let encodedData = try encode(bodyPart)
            encoded.append(encodedData)
        }

        return encoded
    }

    public func writeEncodedData(to fileURL: URL) throws {
        if let bodyPartError = bodyPartError {
            throw bodyPartError
        }

        if FileManager.default.fileExists(atPath: fileURL.path) {
            throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL))
        } else if !fileURL.isFileURL {
            throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL))
        }

        guard let outputStream = OutputStream(url: fileURL, append: false) else {
            throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL))
        }

        outputStream.open()
        defer { outputStream.close() }

        self.bodyParts.first?.hasInitialBoundary = true
        self.bodyParts.last?.hasFinalBoundary = true

        for bodyPart in self.bodyParts {
            try write(bodyPart, to: outputStream)
        }
    }
  • encode() 先判断是否已经出错,bodyParts.first?.hasInitialBoundary = true bodyParts.last?.hasFinalBoundary = true
    这段代码表示第一个part需要一个起始分隔符,最后一个part需要一个结束分隔符,在for循环中的encode(bodyPart)会用到这个判断需要插入分隔符的类型。最后返回的Data格式应该是以boundary分隔开的格式。
    private func encode(_ bodyPart: BodyPart) throws -> Data {
        var encoded = Data()
    //插入起始分隔符,还是中间内容分隔符
        let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
        encoded.append(initialData)
    // 插入headerData
        let headerData = encodeHeaders(for: bodyPart)
        encoded.append(headerData)
    // bodyStreamData
        let bodyStreamData = try encodeBodyStream(for: bodyPart)
        encoded.append(bodyStreamData)
    // 是否需要结束分隔符
        if bodyPart.hasFinalBoundary {
            encoded.append(finalBoundaryData())
        }
        return encoded
    }

你可能感兴趣的:(Alamofire源码解析 - MultipartFormData)