[英]How to upload an image with Alamofire inside parameters
There's a lot of similar questions on here, but i couldn't find an answer that's help me in solving this problem. 这里有很多类似的问题,但是我找不到答案可以帮助我解决这个问题。
What I want to do is upload an image with Alamofire with parameters and the image itself should be part of the parameters. 我想要做的是使用Alamofire上传带有参数的图像,并且图像本身应该是参数的一部分。 For example the parameters should be like this:
例如,参数应如下所示:
["user_id": 1, "picture": 'and here will be the image that i want to upload']
in the response i will be getting the image as a link like this: 在响应中,我将获得图像作为这样的链接:
"/uploads/members/'user_id'/images/member_'user_id'/28121284ase2.jpg"
something similar to that. 类似的东西。
Also the image should be ' jpg, png and not more than 5MB '. 图像也应为“ jpg,png和不超过5MB”。
I'm new to uploading images w\\ API so I don't what to do exactly. 我是使用API上传图片的新手,所以我不知道该怎么做。 I tried every solution I could find in here and google but no luck so far.
我尝试了在这里和Google都能找到的所有解决方案,但到目前为止还没有运气。 Any help would be appreciated.
任何帮助,将不胜感激。
I'm going to assume that you have an instance of UIImage to start with, you'll have to encode it to base64 and send it to your backend as you would any other String parameter. 我将假设您首先有一个UIImage实例,您必须将其编码为base64并将其发送到后端,就像处理其他任何String参数一样。 This should help :
这应该有帮助:
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)
}
}
You can do that by using multipart/form-data request. 您可以通过使用multipart / form-data请求来实现。 your question is relative to this one: Upload image with multipart form-data iOS in Swift
您的问题与这一问题有关: 在Swift中使用多部分表单数据iOS上传图片
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.