Alamofire 上传图片

2021-12-22  本文已影响0人  Look2021
typealias StringVoidBlock = (String?)->(Void)
typealias JSONVoidBlock = (JSON)->(Void)

/// 多图上传,带参数(必须用formdata表单上传)
    /// - Parameters:
    ///   - apiName: 接口方法名
    ///   - method: HTTP请求的方法名(POST、PUT等)
    ///   - params: 需要传递的参数
    ///   - images: 上传的图片数组
    ///   - success: 成功回调
    ///   - fail: 失败回调
    static func upload(apiName:String,method:HTTPMethod,params:[String:Any]?,images:[UIImage],success: JSONVoidBlock?,fail:StringVoidBlock?) {
        
        let fullStr = SERVERURL + apiName
        /// 设置公共参数
        let token = "token" /// 这是你们httpHeader用到的token
        
        let httpHeader: HTTPHeaders = [
            "Authorization": token,
            "Content-type": "multipart/form-data"
        ]
        
        Alamofire.upload(multipartFormData: { (multipartFormData) in
            
            if params != nil {
                for (key, value) in params! {
                    let data_ = "\(value)".data(using: String.Encoding.utf8)!
                    HLog(message: data_)
                    multipartFormData.append(data_, withName: key)
                }
            }

            for index in 0..<images.count {
                let img = images[index]
                if let imgData = img.jpegData(compressionQuality: 0.2) {
                    multipartFormData.append(imgData, withName: "files",fileName: "image_\(index).png", mimeType: "image/png")
                }
            }
            
        }, to: fullStr ,method: method,headers: httpHeader) { (encodingResult) in
            // SessionManager.MultipartFormDataEncodingResult
            print("UPLOAD请求url----->" + fullStr)
            print("UPLOAD请求params-----> \(params ?? [:])")
            
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    /// 上传成功
                    guard response.result.isSuccess else {
                        /// 网络链接错误或者服务器故障
                        if fail != nil {
                            fail!("网络链接错误或者服务器故障")
                        }
                        return
                    }
                    
                    let json = JSON(response.result.value as Any)
                    let msg = json["message"].stringValue
                    let code = json["code"].intValue
                    if code == 200 {
                        /// 成功
                        if success != nil {
                            success!(json["data"])
                        }
                        
                        print(json["data"])
                        
                    }else if code == 401 {
                        /// token 失效,重新登录
                        if fail != nil {
                            fail!("登录失败,请重新登录")
                            ELUser.share.userModel = nil
                            toLogin()
                        }
                    }else {
                        /// 失败
                        if fail != nil {
                            fail!(msg)
                        }
                    }
                }
                
            case .failure(let encodingError):
                if fail != nil {
                    fail!(encodingError.localizedDescription)
                }
            }
        }
    }
上一篇下一篇

猜你喜欢

热点阅读