简体   繁体   中英

I want to upload image to multipart form data using alamofire swift 5

I want to upload png image to URL like postman, i used postman postman screenshot

I used this function to upload png image to url using post method using Alamofire this is upload function, but it return error code 500 Internal server error although it success with code 200 in postman

 static func updateProfileImage(image : UIImage , result : @escaping()->()) {

        if let user = UserDefaults.standard.string(forKey: "mail") , let imgData = image.pngData(){
            Alamofire.upload(
                multipartFormData: { multipartFormData in

                multipartFormData.append("form-data".data(using: .utf8 ,allowLossyConversion: false)!, withName: "Content-Disposition")
                //multipartFormData.append("name".data(using: .utf8 ,allowLossyConversion: false)!, withName: "fileUpload")
        multipartFormData.append(imgData, withName: "fileUpload", mimeType: "image/png")
        },
                to: URLs.profileImage+user,method: .post,
                encodingCompletion: { encodingResult in
                    switch encodingResult {
                    case .success(let upload, _, _):
                        upload.response { response in
                            print(response)
                        }
                    case .failure( _):
                        print("error")
                    }
                }
            )
        }

I have code of multipart data request follows, I hope this will help you.

    Alamofire.upload( multipartFormData: { multipartFormData in

        // parameters is method arguments in my webs ervice call method
        for (key, value) in parameters {
            if let data = (value as! String).data(using: .utf8) {
                multipartFormData.append(data, withName: key)
            }
        }

        let imageData = image?.jpegData(compressionQuality: 0.5)

        multipartFormData.append(imageData!, withName: "profile_image", fileName: "profileImage", mimeType: "image/jpeg")

    // getURL(.addProfile) will create url, method from my structure
    // getHeaders() will return required header from that method
    }, to: getURL(.addProfile), headers: getHeaders(), encodingCompletion: { encodingResult in

        switch encodingResult {

        case .success(let upload, _, _):

            upload.response(completionHandler: { (defaultDataResponse) in

                guard let httpResponse = defaultDataResponse.response else {
                    completion(nil, defaultDataResponse.error)
                    return
                }

                if httpResponse.statusCode == 200 {

                    // Success Code

                } else {
                    // Failed code
                }
            })

        case .failure(let encodingError):

            // Failed code.
        }
    })

Try this

func generateBoundary() -> String {
    return "Boundary-\(NSUUID().uuidString)"
}

//Set Headers with required auth

let boundary = generateBoundary()

let headers = ["content-type": "multipart/form-data; boundary=\(boundary)",
              "Content-Type": "application/json",
              "cache-control": "no-cache"]

//Api Call

Alamofire.upload(multipartFormData:{ multipartFormData in

            if let image = imageData {
                multipartFormData.append(image, withName: "<param_key>", fileName: objIdentityDetails.fileName ?? (String(Date().timeIntervalSince1970) + ".jpeg"), mimeType: "image/jpeg")
            }
            for (key, value) in parameters {
                multipartFormData.append(value?.data(using: String.Encoding.utf8) ?? Data(), withName: key)
            }},
                         usingThreshold:UInt64.init(),
                         to: try! <URL>,
                         method: .post,
                         headers: headers,
                         encodingCompletion: { encodingResult in
                            switch encodingResult {
                            case .success(let upload, _, _):
                                upload.responseObject { (response: <model>) in
                                    switch response.result {
                                    case .failure (let error):
                                        //Error 
                                    case .success (let responseObject):
                                       //response
                                    }
                                }
                            case .failure(let encodingError):
                                //Error 
                            }
        })

You can use this following code to upload:


Alamofire.upload(multipartFormData:{ multipartFormData in  multipartFormData.append(img, withName: "image", fileName: "image.png", mimeType: "image/png")  },

"img" - Is Your Image Data & "withName" - Is Your Name In Postman & "fileName" - Your Image Name Which You Want To Upload

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