使用alamofire路由器上传文件

时间:2014-10-16 19:53:29

标签: swift alamofire

如何使用alamofire路由器上传文件?苦苦挣扎。

我也很感兴趣如何使用Alamofire路由器在同一请求中上传文件和参数。

谢谢!

1 个答案:

答案 0 :(得分:0)

我使用以下代码上传图片。对于给定的文件类型,您应该能够相应地调整multipartEncoding块。

let json: [String : Any] = ["key", "value"]

let image = UIImage(named: "Something")!

guard let imageData = UIImagePNGRepresentation(image) else {
    // We couldn't convert the image into data :(
}

let multipartEncoding: (MultipartFormData) -> Void = { multipartFormData in
    multipartFormData.append(imageData, withName: "image", fileName: "image.png", mimeType: "image/png")
}

let request = Router.uploadPicture(parameters: json) // This is just a plain POST

sessionManager.upload(
    multipartFormData: multipartEncoding,
    with: request,
    encodingCompletion: { (encodingResult) in
        switch encodingResult {
        case .success(let request, _, _):
            request.validate().responseJSON(completionHandler: { (dataResponse) in
                if let error = dataResponse.result.error {
                    // Network request failed :(
                }
                // SUCCESS!
            })
        case .failure(_):
            // Couldn't encode the image :(
        }
})

这假设您的Router看起来像这样。

enum Router: URLRequestConvertible {

    case uploadPicture(parameters: Parameters)

    static var baseUrl = "https://website.com/"

    var method: HTTPMethod {
        switch self {
        case .uploadPicture(_):
            return .post
        }
    }

    var path: String {
        switch self {
        case .uploadPicture(_):
            return "api/upload-picture/"
        }
    }

    // MARK: - URLRequestConvertible

    func asURLRequest() throws -> URLRequest {

        let url = try Router.baseUrl.asURL().appendingPathComponent(path)
        var urlRequest = try URLRequest(url: url, method: method)
        var encodedUrlRequest: URLRequest?

        switch self {

        case .uploadPicture(let parameters):
            encodedUrlRequest = try? JSONEncoding.default.encode(urlRequest, with: parameters)

        }

        return encodedUrlRequest ?? urlRequest
    }
}