[英]How to upload an image with Alamofire inside parameters
這里有很多類似的問題,但是我找不到答案可以幫助我解決這個問題。
我想要做的是使用Alamofire上傳帶有參數的圖像,並且圖像本身應該是參數的一部分。 例如,參數應如下所示:
["user_id": 1, "picture": 'and here will be the image that i want to upload']
在響應中,我將獲得圖像作為這樣的鏈接:
"/uploads/members/'user_id'/images/member_'user_id'/28121284ase2.jpg"
類似的東西。
圖像也應為“ jpg,png和不超過5MB”。
我是使用API上傳圖片的新手,所以我不知道該怎么做。 我嘗試了在這里和Google都能找到的所有解決方案,但到目前為止還沒有運氣。 任何幫助,將不勝感激。
我將假設您首先有一個UIImage實例,您必須將其編碼為base64並將其發送到后端,就像處理其他任何String參數一樣。 這應該有幫助:
extension UIImage {
func toBase64() -> String? {
guard let imageRectoData = jpeg(.low) else {
return nil
}
return imageRectoData.base64EncodedString()
}
enum JPEGQuality: CGFloat {
case lowest = 0
case low = 0.25
case medium = 0.5
case high = 0.75
case highest = 1
}
/// Returns the data for the specified image in JPEG format.
/// If the image object’s underlying image data has been purged, calling this function forces that data to be reloaded into memory.
/// - returns: A data object containing the JPEG data, or nil if there was a problem generating the data. This function may return nil if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format.
func jpeg(_ jpegQuality: JPEGQuality) -> Data? {
return jpegData(compressionQuality: jpegQuality.rawValue)
}
}
您可以通過使用multipart / form-data請求來實現。 您的問題與這一問題有關: 在Swift中使用多部分表單數據iOS上傳圖片
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.