パラメータ(multipartformdata)を含むファイルをアップロードしようとしていますが、新しいバージョンのAlamofire 5ではそれを実行できません。Alamofire5の経験がある場合は、私と共有してください。
func uploadPluckImage(imgData : Data, imageColumnName : String, url:String,httpmethod:HTTPMethod,completionHandler: @escaping (NSDictionary?, String?) -> ()){
let token = UserDefaults.standard.string(forKey: PrefKeys.loginToken) ?? ""
let authorization = ["Authorization" : "Bearer \(token)"]
let parameters: Parameters?
parameters = [
"garbageCollector": 0,
"stuff_uuid": "2b4b750a-f4a6-4d61-84ce-7c42b5c030ee",
"delete_file" : ""
]
let headers : HTTPHeader?
headers = ["Authorization" : "Bearer \(token)"]
let imageURl = "http://68.183.152.132/api/v1/stuff/uploader"
AF.upload(multipartFormData: { (multipart: MultipartFormData) in
let imageData = self.firstImage.image?.jpegData(compressionQuality: 0.7)
multipart.append(imageData, withName: "file", fileName: "file.png", mimeType: "image/png")
for (ker, value) in parameters!{
multipart.append(value as! String).data(using: .utf8)!, withName: key)
}
},usingThreshold: UInt64.init(),
to: imageURl,
method: .post,
headers: headers,
encodingCompletion: { (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Uploading")
})
break
case .failure(let encodingError):
print("err is \(encodingError)")
break
}
})
}
あなたはルータURLRequestConvertibleを使用してそれを行うことができます
static func performMultiPartFile<T:Decodable>(imageData: Data, route:APIRoute,decoder: JSONDecoder = JSONDecoder(), completion: @escaping (_ result: T?, _ error: String?) -> ()) {
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData, withName: "image", fileName: "iosImage.jpg", mimeType: "image/jpg")
}, with: route) { (encodingResult) in
switch encodingResult {
case .success(let upload, _, _):
upload.responseString { (response) in
if response.result.isSuccess {
if let JSON = response.result.value {
debugPrint("✅ Respons Object >>>> " + String(describing: JSON))
do {
let result = try JSONDecoder().decode(T.self, from: JSON.data(using: .utf8)!)
debugPrint("✍️ Result: " + String(describing: result))
completion(result, nil)
} catch let error { // mapping fail
debugPrint("❌ Error in Mapping" + String(describing: error))
completion(nil, String(describing: error))
}
}
} else {
debugPrint("❌ ???? Response fail : \(response.result.description)")
completion(nil, (response.result.error?.localizedDescription)!)
}
}
case .failure(let encodingError):
completion(nil, String(describing: encodingError))
}
}
}
これはSwift Alamofire 5の5つのアプリから画像と動画をアップロードする方法
画像
/**
Send Image to server
*/
func Post(imageOrVideo : UIImage?){
let headers: HTTPHeaders = [
/* "Authorization": "your_access_token", in case you need authorization header */
"Content-type": "multipart/form-data"
]
AF.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(imageOrVideo!.jpegData(compressionQuality: 0.5)!, withName: "upload_data" , fileName: "file.jpeg", mimeType: "image/jpeg")
},
to: "http://ip.here.--.--/new.php", method: .post , headers: headers)
.response { resp in
print(resp)
}
}
一時的なリソースを作成し、一時的なURLを使用できます(ビデオに適しています):
/**
Send video to server
*/
func PostVideoUrl(url : URL){
let headers: HTTPHeaders = [
"Content-type": "multipart/form-data"
]
AF.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(url, withName: "upload_data" , fileName: "movie.mp4", mimeType: "video/mp4")
},
to: "http://ip.here.--.--/newVideo.php", method: .post , headers: headers)
.response { resp in
print(resp)
}
}