I have a multiPartFormData upload for an image that needs to send my .php the id that wants to upload the info to
I want to know how to add parameters to alamofire 5 upload
When I try to autocomplete or look on the internet for some1 that already did it I cant find anything.
alamofire 5
xCode 10
swift 5
iOs 12.4
macOS 10.14.5 (18F132)
This is my code so far.
let urlAlert = URL(string: urlAlertS)!
let headerS: HTTPHeaders = [
"Authorization": "Bearer (HelperGlobalVars.shared.access_token)",
"Accept": "application/json"
]
let parameterS: Parameters = ["alertId": nId ?? 1,
"image": image]
AF.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(image!.jpegData(compressionQuality: 0.5)!, withName: "upload_data" , fileName: "file.jpeg", mimeType: "image/jpeg")
},
to: urlAlert, method: .put , headers: headerS)
.response { resp in
print(resp)
}
having the same issue, kindly share upload multipart with parameters method implementation.
Create a parameter-dictionary [String: Data] and then append the entries before the actual file
let parameter = createParameterDictionary(...)
if let parameter = parameter {
AF.upload(multipartFormData: { multipartFormData in
for (key, value) in parameter {
multipartFormData.append(value, withName: key)
multipartFormData.append(image!.jpegData(compressionQuality: 0.5)!, withName: "upload_data" , fileName: "file.jpeg", mimeType: "image/jpeg")
},
to: urlAlert, method: .put , headers: headerS)
.response { resp in
print(resp)
}
private func createParameterDictionary(...) -> [String: Data]? {
var params: [String: Data] = [:]
do {
params["alertId"] = parameter.someSTRING.data(using: .utf8)!
params["image"] = try JSONEncoder().encode(someThing)
return params
} catch {
return nil
}
}
let parameterS: Parameters = ["alertId": nId ?? 1]
AF.upload(
multipartFormData: { multipartFormData in
for (key, value) in parameterS {
if let temp = value as? String {
multipartFormData.append(temp.data(using: .utf8)!, withName: key)
}
if let temp = value as? Int {
multipartFormData.append("(temp)".data(using: .utf8)!, withName: key)
}
if let temp = value as? NSArray {
temp.forEach({ element in
let keyObj = key + "[]"
if let string = element as? String {
multipartFormData.append(string.data(using: .utf8)!, withName: keyObj)
} else
if let num = element as? Int {
let value = "(num)"
multipartFormData.append(value.data(using: .utf8)!, withName: keyObj)
}
})
}
}
multipartFormData.append(image!.jpegData(compressionQuality: 0.5)!, withName: "image" , fileName: "file.jpeg", mimeType: "image/jpeg")
},
to: urlAlert, method: .post , headers: headerS)
.validate(statusCode: 200..<300)
.response { resp in
switch resp.result{
case .failure(let error):
print(error)
case.success( _):
print("馃ザ馃ザResponse after upload Img: (resp.result)")
}
}
Sorry, we use our GitHub project for bug reports and feature requests. In the future, you should open questions like this on Stack Overflow and tag alamofire.
Cheers. 馃嵒
From our Contribution Guidelines
We don't use GitHub as a support forum. For any usage questions that are not specific to the project itself, please ask on Stack Overflow instead. By doing so, you'll be more likely to quickly solve your problem, and you'll allow anyone else with the same question to find the answer. This also allows maintainers to focus on improving the project for others.
i found solve to this issue , try this code
//MARK: Upload Images with Params API's
func upload(icon: Data, image : Data, params: [String: Any]) {
let urlString = "Your URL String"
let headers: HTTPHeaders = [
"Content-type": "multipart/form-data",
"Accept": "application/json"
]
AF.upload(
multipartFormData: { multipartFormData in
for (key, value) in params {
if let temp = value as? String {
multipartFormData.append(temp.data(using: .utf8)!, withName: key)
}
if let temp = value as? Int {
multipartFormData.append("(temp)".data(using: .utf8)!, withName: key)
}
if let temp = value as? NSArray {
temp.forEach({ element in
let keyObj = key + "[]"
if let string = element as? String {
multipartFormData.append(string.data(using: .utf8)!, withName: keyObj)
} else
if let num = element as? Int {
let value = "(num)"
multipartFormData.append(value.data(using: .utf8)!, withName: keyObj)
}
})
}
}
multipartFormData.append(icon, withName: "icon", fileName: "icon.png", mimeType: "icon/png")
multipartFormData.append(image, withName: "registerImage", fileName: "registerImage.png", mimeType: "registerImage/png")
},
to: urlString, //URL Here
method: .post,
headers: headers)
.responseJSON { (resp) in
defer{SVProgressHUD.dismiss()}
print("resp is \(resp)")
}
}
Create a parameter-dictionary [String: Data] and then append the entries before the actual file
let parameter = createParameterDictionary(...) if let parameter = parameter { AF.upload(multipartFormData: { multipartFormData in for (key, value) in parameter { multipartFormData.append(value, withName: key) multipartFormData.append(image!.jpegData(compressionQuality: 0.5)!, withName: "upload_data" , fileName: "file.jpeg", mimeType: "image/jpeg") }, to: urlAlert, method: .put , headers: headerS) .response { resp in print(resp) } private func createParameterDictionary(...) -> [String: Data]? { var params: [String: Data] = [:] do { params["alertId"] = parameter.someSTRING.data(using: .utf8)! params["image"] = try JSONEncoder().encode(someThing) return params } catch { return nil } }
it's work for me
This is work with params.
func uploadImage(isUser:Bool, endUrl: String, imageData: Data?, parameters: [String : Any], onCompletion: ((_ isSuccess:Bool) -> Void)? = nil, onError: ((Error?) -> Void)? = nil){
headerFile()
AF.upload(multipartFormData: { multipartFormData in
for (key, value) in parameters {
if let temp = value as? String {
multipartFormData.append(temp.data(using: .utf8)!, withName: key)
}
if let temp = value as? Int {
multipartFormData.append("\(temp)".data(using: .utf8)!, withName: key)
}
if let temp = value as? NSArray {
temp.forEach({ element in
let keyObj = key + "[]"
if let string = element as? String {
multipartFormData.append(string.data(using: .utf8)!, withName: keyObj)
} else
if let num = element as? Int {
let value = "\(num)"
multipartFormData.append(value.data(using: .utf8)!, withName: keyObj)
}
})
}
}
if let data = imageData{
multipartFormData.append(data, withName: "file", fileName: "\(Date.init().timeIntervalSince1970).png", mimeType: "image/png")
}
},
to: endUrl, method: .post , headers: headers)
.responseJSON(completionHandler: { (response) in
print(response)
if let err = response.error{
print(err)
onError?(err)
return
}
print("Succesfully uploaded")
let json = response.data
if (json != nil)
{
let jsonObject = JSON(json!)
print(jsonObject)
}
})
}
Most helpful comment
Create a parameter-dictionary [String: Data] and then append the entries before the actual file