Search code examples
iosswiftswift2alamofire

Upload Data to Alamofire Using the Usual Way like Posting other data


    let parameters = [
        "profile_picture" : "\(profilePictureData)",
    ]

    Alamofire.request(.POST, UPDATE_PROFILE_PICTURE_URL + "token=\(userToken)", parameters: parameters, encoding: .JSON, headers: AUTHENTICATION_HEADER).response { (request, response, data, errorType) -> Void in

        if(data != nil) {
            let responseStr:NSString = NSString(data:data!, encoding:NSUTF8StringEncoding)!
            print(responseStr);

            let resultObject: APIResults = APIResults(JSONDecoder(data!));
            let responseCode: Int = Int(resultObject.code!)!;

            if(responseCode == 200) {
                succeeded = true;

            }
        }
    }

So far here is my code, I am trying to post my profilePictureData which is a NSData to server just like how I would normally send Strings or Int. I put the profilePictureData to the body parameter. This always fail and the server returns error.

How should I send my Image Data to server?

Please help. Thank you


Solution

  • Use this as a model. Just edit it accordingly.

    Alamofire.upload(.POST,
            URLString: "https://example.com/api/v1/users/\(user_id)/profile_pic.json?auth_token=\(auth_token)",
            multipartFormData: { multipartFormData in
                multipartFormData.appendBodyPart(data: imageData, name: "avatar", fileName: "avatar_img.png", mimeType: "image/png")
            },
            encodingCompletion: { encodingResult in
    
                switch encodingResult {
                    case .Success (let upload, _, _):
                        upload.responseJSON { request, response, data, error in
    
                        // Do whatever 
    
                        } 
                    case .Failure (let encodingError):
                        //Realistically, I don't expect this to ever trigger, but I guess if the user uses some very weird image format...
                }
    
            })