前言:基于Alamofire4.5网络框架开发的Swift项目中上传文件和图片代码参考。
上传文件
extension HttpRequestService {typealias UploadDoneBlock = (_ dict:[String : Any]) -> Void//成功blockfunc uploadEcgFileWithGatherRecord(model :RecordModel, fileName : String, zipData : NSData, md5 : String, success:@escaping UploadDoneBlock, fail:@escaping FailedBlock) {let urlStr = HttpConfig.RequestUrlHeader.httpRequestUrlHeader + HttpConfig.RequestApi.uploadRecordApi//构造发送参数let parameters: Parameters = ["user_id":model.userId]//请求头let localToken = Tools.readFromUserDefault(key: localToken)!// 头部需要的内容包装let headers: HTTPHeaders = [ "Accept": "application/json;charset=utf-8","lang":"en-US","token": localToken]Alamofire.upload(multipartFormData: { (formData) in// "fname" 这里是服务器对应好的字段formData.append(zipData as Data, withName: "fname", fileName: fileName, mimeType:"application/zip")//拼接参数for (key, value) in parameters {let v = value as! StringformData.append(v.data(using: String.Encoding.utf8)!, withName: key)}
// usingThreshold 指的是传入文件大小最大值}, usingThreshold: (50*1024*1024), to: URL.init(string: urlStr)!, method: HTTPMethod.post, headers: headers) { (encodingResult) inswitch encodingResult {case .success(let upload, _, _):upload.responseJSON { response inif let jsonValue = response.result.value {let json = JSON(jsonValue)print("上传记录json:\(json)")let code = json["code"].intif code == HttpConfig.ErrorCode.HttpOK {let dict = json["data"].dictionaryObjectsuccess(dict!) } else {fail("")}}}case .failure(_):self.networkErrorHint() // 网络错误处理 }}}
复制代码
图片上传
typealias UploadUserIconSuccess = (_ dict:[String : Any]) -> Void//成功blockfunc uploadUserIcon(fileName: String, imgData: NSData, success:@escaping UploadUserIconSuccess, fail:@escaping FailedBlock ) {let urlStr = HttpConfig.RequestUrlHeader.httpRequestUrlHeader + HttpConfig.RequestApi.uploadUserIconApi//请求头let localToken = Tools.readFromUserDefault(key: localToken)!// 头部需要的内容包装let headers: HTTPHeaders = [ "Accept": "application/json;charset=utf-8","lang":"en-US","token": localToken]Alamofire.upload(multipartFormData: { (formData) in// 参数解释://withName:和后台服务器的name要一致 ;fileName:可以充分利用写成用户的id,但是格式要写对; mimeType:规定的,要上传其他格式可以自行百度查一下formData.append(imgData as Data, withName: "fname", fileName: fileName, mimeType:"image/jpeg")//如果需要上传多个文件,就多添加几个append,或则for-in语句进行循环处理
// formData.append(imgData as Data, withName: "fname", fileName: fileName, mimeType:"image/jpeg")
// formData.append(imgData as Data, withName: "fname", fileName: fileName, mimeType:"image/jpeg")}, usingThreshold: (10*1024*1024), to: URL.init(string: urlStr)!, method: HTTPMethod.post, headers: headers) { (encodingResult) inswitch encodingResult {case .success(let upload, _, _):upload.responseJSON { response inif let jsonValue = response.result.value {let json = JSON(jsonValue)print("上传头像json:\(json)")let code = json["code"].intif code == HttpConfig.ErrorCode.HttpOK {let dict = json["data"].dictionaryObjectsuccess(dict!)} else {let msg = json["msg"].stringHudToast.toastError(error: msg!)}}}case .failure(_):self.networkErrorHint()}}}
复制代码