前言:基于Alamofire4.5网络框架开发的Swift项目中上传文件和图片代码参考。
上传文件
extension HttpRequestService {
typealias UploadDoneBlock = (_ dict:[String : Any]) -> Void//成功block
func 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! String
formData.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) in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if let jsonValue = response.result.value {
let json = JSON(jsonValue)
print("上传记录json:\(json)")
let code = json["code"].int
if code == HttpConfig.ErrorCode.HttpOK {
let dict = json["data"].dictionaryObject
success(dict!)
} else {
fail("")
}
}
}
case .failure(_):
self.networkErrorHint() // 网络错误处理
}
}
}
图片上传
typealias UploadUserIconSuccess = (_ dict:[String : Any]) -> Void//成功block
func 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) in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if let jsonValue = response.result.value {
let json = JSON(jsonValue)
print("上传头像json:\(json)")
let code = json["code"].int
if code == HttpConfig.ErrorCode.HttpOK {
let dict = json["data"].dictionaryObject
success(dict!)
} else {
let msg = json["msg"].string
HudToast.toastError(error: msg!)
}
}
}
case .failure(_):
self.networkErrorHint()
}
}
}
OC版本看之前的一篇文章