Upload the image to the server with the latest Alamofire (swift 4.1) (with parameters) post method

Upload pictures to the server with the latest Alamofire (swift 4.1) (with parameters)

1. Prepare parameters

let image = UIImage(named: "xxx")
//The parameter after converting the picture to JPEG type data is compression ratio
let jpegImage = UIImageJPEGRepresentation(image!, 0.5)
//Parameters to be passed (such as the encrypted uid with the user)
 let uid = ["uid" : user.uid]
 let ecodeUid = EncryptionHelper.getParamsString(uid as [String : AnyObject])
 //Turn the competition into data
let ecodeData = ecodeUid.data(using: .utf8)

2. Start to upload

//All codes are as follows
Alamofire.upload(multipartFormData: { (multipartFormData) in
    multipartFormData.append(ecodeData!, withName: "data")
    multipartFormData.append(jpegImage!, withName: "avatar", fileName: "avatar"+".jpeg", mimeType: "image/jpeg")
            }, to: "https://www.ka5188.com/app/api/v1/user/uploadImg" , encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        if let data = response.data {
                            let responseJson = JSON(data: data)
                            if responseJson["status"].intValue == 1 {
                                //Upload succeeded, refresh current Avatar
                            } else {
                               let msg = responseJson["msg"].stringValue
                case .failure(let encodingError):
                    self.showMessage("Upload picture failed")

Description and notes

//What to pay attention to 
 multipartFormData.append(ecodeData!, withName: "data")
//The first parameter "ecodeData" is our encrypted binary uid
 /Second parameter "data"
The server gets the encrypted uid with this field name (I think it should use "uid")

multipartFormData.append(jpegImage!, withName: "avatar", fileName: "avatar"+".jpeg", mimeType: "image/jpeg")
//Take a parameter "JPEG image", which is our encrypted binary image stream
 //With two parameters "withName", the background obtains the picture through the west field
 //With three parameters "fileName", background check image type, mainly the suffix
 //With four parameters "mimeType", the type of file transferred.
Note: 1. Since the second parameter and the third parameter are confused, the pilot upload fails
      2. Because the third parameter is not suffixed with ". jpeg", background output (file format is not supported)
      3. The third parameter, mimeType, is a picture
      Here's the official explanation, and some of our background php code


The official explanation is as follows

Backend code

Tags: Swift JSON PHP

Posted on Thu, 02 Apr 2020 00:14:55 -0700 by gooney0