// // Http+UploadImage.swift // ADHTuanCan // // Created by 敖德亨 on 2023/11/9. // import Foundation import Alamofire import SwiftyUserDefaults import HandyJSON extension MCHttpUtil{ @discardableResult static func uploadImg(imageDates : [Data] , url : String ,success:(([PhotoUrlModel])->Void)?,error:((_ msg : String)->Void)? = nil){ var imgUrlList : [PhotoUrlModel]? = [] for item in imageDates { let imageDate = item MCHttpUtil.upLoadImgOneByOne(imageDate: imageDate, Url: url, success: { model in imgUrlList?.append(model) if imgUrlList?.count == imageDates.count{ success!(imgUrlList!) } }, error: { errorMsg in error!("\(errorMsg)") return }) } } @discardableResult static func upLoadImgOneByOne(imageDate : Data , Url : String,success:((_ model : PhotoUrlModel)->Void)?,error:((_ msg : String)->Void)?){ let requestUrl = Defaults[\.BaseUrl]! + Url var headers : HTTPHeaders = ["Authorization":"Basic c3dvcmQ6c3dvcmRfc2VjcmV0", "Tenant-Id":"000000","content-Type":"application/json;charset=utf-8"] if let _ = Defaults[\.UserToken]{ headers["Blade-Auth"] = Defaults[\.UserToken] } if LanguagesUtil.isEnLanguage(){ headers["ce_identification"] = "en" } Alamofire.upload(multipartFormData: { multipartFormData in let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let date = Date() let dateString = dateFormatter.string(from: date) multipartFormData.append(imageDate, withName: "file",fileName: "\(dateString).jpeg",mimeType: "image/jpeg") }, to: requestUrl,headers: headers, encodingCompletion: {encodingResult in switch encodingResult{ case .success(let upload,_,_): upload.responseJSON { response in //解包 guard let result = response.result.value else { return} print("json:\(result)") if let d = result as? Dictionary{ if d.keys.contains("code"){ if Convert.toInt(d["code"]) != 200{ error!("\(Convert.toString(d["msg"]) ?? "failing")") }else{ let dict : [String : String] = d["data"] as! [String : String] if Convert.toString(dict["link"]).isEmptyStr{ error!("\(Convert.toString(dict["msg"]) ?? "failing")") }else{ let model = PhotoUrlModel() model.attachId = Convert.toString(dict["attachId"]) model.link = Convert.toString(dict["link"]) model.url = Convert.toString(dict["url"]) model.name = Convert.toString(dict["name"]) success!(model) } } } } } //获取上传进度 upload.uploadProgress(queue: DispatchQueue.global(qos: .utility)){progress in print("图片上传进度:\(progress.fractionCompleted)") } case .failure(let encodingError)://打印连接失败原因 print(encodingError) error!("\(encodingError)") } }) } }