繁体   English   中英

如何使用Alamofire内部参数上传图像

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM