Home > Software design >  Multipart Form Data POST with spesific JSON Requirement
Multipart Form Data POST with spesific JSON Requirement

Time:12-23

I'm new to Alamofire and now using Alamofire 5. I want to create a POST request with multipart form data, but there's a specific requirement for the JSON body. Here it is:

"item": [
    {
        "name": "Upload image",
        "request": {
            "method": "POST",
            "header": [],
            "body": {
                "mode": "formdata",
                "formdata": [
                    {
                        "key": "files[]",
                        "type": "file",
                        "src": []
                    },
                    {
                        "key": "mode",
                        "value": "public",
                        "type": "text"
                    }
                ]
            },
            "url": {
                "raw": "https://jsonplaceholder.typicode.com/api/image/upload",
                "protocol": "https",
                "host": [
                    "jsonplaceholder",
                    "typicode",
                    "com"
                ],
                "path": [
                    "api",
                    "image",
                    "upload"
                ]
            }
        },
        "response": []
    },
]

Anyone can help me how to post the data but with multipart form data? Please help. (It's okay if the POST request is using URLSession)

CodePudding user response:

Whatever I understand from your question and comments, I have created a method from your previous question.

func postImage(images: [UIImage],imgName : [String]) {
    var arrFormData = [[String:Any]]()
    var imgDataArray: [Data] = []

    for image in images {
        guard let imgData = image.jpegData(compressionQuality: 0.50) else { return }
        
        imgDataArray.append(imgData)
    }
    let param1: [String: Any] = [
            "key":"files[]",
            "type": "file",
            "src": imgName
        ]
    let param2: [String: Any] = [
        "key": "mode",
        "value": "public",
        "type": "text"
        ]
    var arrParam = [[String:Any]]()
    arrParam.append(param1)
    arrParam.append(param2)
    arrFormData.append(contentsOf: arrParam)
    var param : [String:Any] = [:]
    if let theJSONData = try? JSONSerialization.data(
        withJSONObject: arrFormData,
        options: []) {
        let theJSONText = String(data: theJSONData,
                                   encoding: .ascii)
        print("JSON string = \(theJSONText!)")
        param = ["formData" : theJSONText ?? ""]
    }
    print(param)
    Alamofire.upload(multipartFormData: {
        multipartFormData in
         for i in 0..<images.count{
            if let imageData = images[i].jpegData(compressionQuality: 0.6) {
                multipartFormData.append(imageData, withName: "file", fileName: "name.png", mimeType: "image/png")
            }
        }

        for (key, value) in param {
            multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
        }
    }, usingThreshold: 10 * 1024 * 1024,to: apiurl, method: .post, headers: headers, encodingCompletion: { encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.responseJSON {
                response in
                print(response.result)
            }
        case .failure(let encodingError):
            print(encodingError)
        }
    })
}
  • Related