简体   繁体   中英

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. 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 '.

I'm new to uploading images w\\ API so I don't what to do exactly. I tried every solution I could find in here and google but no luck so far. 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. 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. your question is relative to this one: Upload image with multipart form-data iOS in Swift

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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