我正在使用Alamofire来管理我的应用程序中的网络 我用来将图像上传到服务器的API需要两个参数,即图像名称和图像数据(以64为基数的字符串) 我知道如何使用此代码将图像转换为base64
class func convertImageToBase64(image: UIImage) -> String {
let imageData = UIImagePNGRepresentation(image)!
return imageData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)
}
但是我不知道如何获得图像名称?! 第二,如果我获得了图像名称,如何将图像上传到服务器,谁能解释一下上传图像的Alamofire代码?
这是我的API
Web方法:
{ “ FileName”:“ Hydrangeas.jpg”, “ ImageData”:“ base64string” }
注释: FileName:照片的选择文件名 ImageData:以64为基数的字符串表示图像字节
提前谢谢
答案 0 :(得分:0)
步骤01:
在顶部导入照片库
import Photos
使用UIImagePickerController()这样获得图像
var base64Image: String?
var fileName: String?
override func viewDidLoad() {
super.viewDidLoad()
let image = UIImagePickerController()
image.delegate = self
image.sourceType = UIImagePickerController.SourceType.photoLibrary
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
if let asset = info[UIImagePickerController.InfoKey.phAsset] as? PHAsset {
if let fileName = (asset.value(forKey: "filename")) as? String {
self.fileName = fileName
}
}
base64Image = convertImageToBase64(image: image)
}
self.dismiss(animated: true, completion: nil)
}
func convertImageToBase64(image: UIImage) -> String {
let imageData = image.pngData()!
return imageData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)
}
步骤02: 像这样在您的参数中设置base64Image
{ "FileName":"\(fileName)", "ImageData":"\(base64Image)" }