Home > Net >  Swift form-data using Alamofire 5 with parameters
Swift form-data using Alamofire 5 with parameters

Time:12-29

I am beginner iOS developer and I don't know how to upload a file using Alamofire 5, I know there are a lot of similar questions, but all the topics here are from very old versions and I couldn't get it working. I tried this code, but I couldn't fit to my case, it gives me success, but file is not uploaded and the result I get is not what I get in postman. This is the code:

func uploadFile(_ parameters: Parameters) {
    
    
    AF.upload(multipartFormData: { multipartFormData in
        
        URLEncoding.default.queryParameters(parameters).forEach { (key, value) in
            if let data = value.data(using: .utf8) {
                multipartFormData.append(data, withName: key)
            }
        }

    }, to: url)
        .responseDecodable(of: FileCreation.self) { response in
            switch response.result {
            case .success(let data):
                print(data, "success")
            case .failure(let error):
                print(error)
            }
        }
    
}

usage:

@IBAction func upload(_ sender: UIButton) {
    
    guard let data = image?.jpegData(compressionQuality: 0.5)! else { return }
    
    let parameters = ["addFiles": data]
    
    uploadFile(parameters)
    
}

Here's Xcode output:

enter image description here

Here you can see postman response after I upload file:

enter image description here

CodePudding user response:

Alamofire.upload(multipartFormData: {
    multipartFormData in

        if let imageData = image[0].jpegData(compressionQuality: 0.6) {
            multipartFormData.append(imageData, withName: "addFiles", fileName: "file.pdf", mimeType: "application/pdf")
        }

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

    case .failure(let encodingError):

        break
    }
})

CodePudding user response:

Try This

func uploadFilesToServer(_ url: String, method: HTTPMethod, parameters: [String:Any]?, file: [String:Any]?, fileType: String, fileName: String, headers:HTTPHeaders?, completionHandler: @escaping (_ result: Data?, _ success: Bool, _ status: String) -> ()) {
    var status = Bool()
    var message = String()
    let url = URL(string: url)
    AF.upload(multipartFormData: { multiPart in
        if let files = file {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "MM-dd-yyyy-hh-mm-ss"
            let dateString = dateFormatter.string(from: Date())
            for (key, value) in files {
                if fileType == "pdf" {
                    let filePath = URL(fileURLWithPath: value as! String)
                    multiPart.append(filePath, withName: "\(key)", fileName: fileName, mimeType: "file/pdf")
                } else {
                    multiPart.append(value as! Data, withName: "\(key)", fileName: "Uploads\(dateString).png", mimeType: "image/png")
                }
            }
        }
        if let params = parameters {
            for (key, value) in params {
                multiPart.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
            }
        }
    }, to: url!, method: method, headers: headers ?? nil)
    .validate()
    .uploadProgress(closure: { progress in
        print(progress)
    })
    .responseJSON { response in
        switch response.result {
        case .success(let responseData):
            print(responseData)
        case .failure(let networkErr):
            switch networkErr {
            case .responseSerializationFailed(reason: _):
                message = "Something went wrong"
            case .sessionTaskFailed(error: let err):
                message = err.localizedDescription
            default:
                message = "Something went wrong"
            }
            completionHandler(nil, false, message)
            break
        }
    }
}

usage

uploadFilesToServer(url, method: .post, parameters: params, file: uploadFile, fileType: "pdf", fileName: fileNme, headers: tokenHeader) { [self] responseData, isSuccess, responseMsg in
    if isSuccess {
                    
    } else {
                    
    }
}
  • Related