Multiple File Upload with Array of Parameters Using Alamofire

Upload multiple images in Alamofire

There are two ways to send multiple files.

  1. You can use a unique name for each file (in this case, name values of image0, image1, etc.):

    for (index, image) in images.enumerated() {
    multipartFormData.append(UIImagePNGRepresentation(image)!, withName: "image\(index)", fileName: "image\(index).png", mimeType: "image/png")
    }

    That results in a $_FILES of:

    $_FILES =     {
    image0 = {
    error = 0;
    name = "image0.png";
    size = 23578;
    "tmp_name" = "/tmp/php1bc19G";
    type = "image/png";
    };
    image1 = {
    error = 0;
    name = "image1.png";
    size = 338685;
    "tmp_name" = "/tmp/phpcGS5d6";
    type = "image/png";
    };
    };

    (Ignore the format of this output, but rather just focus on the key/value combinations in this nested directory structure: In terms of what this output is, I had web service send $_FILES back as JSON, I then let Alamofire parse it, and this is how the resulting dictionary was output in my client app.)

  2. Alternatively, you can use an array for the name by including a [] after the field name, e.g., literally image[]:

    for (index, image) in images.enumerated() {
    multipartFormData.append(UIImagePNGRepresentation(image)!, withName: "image[]", fileName: "image\(index).png", mimeType: "image/png")
    }

    That results in the following to be received on the server:

    $_FILES =     {
    image = {
    error = (
    0,
    0
    );
    name = (
    "image0.png",
    "image1.png"
    );
    size = (
    23578,
    338685
    );
    "tmp_name" = (
    "/tmp/phpI4XrwU",
    "/tmp/php3kVhhl"
    );
    type = (
    "image/png",
    "image/png"
    );
    };
    };

It just depends upon how the web service was expecting the request to be created.

Multipart form data upload with multiple images + parameters (Alamofire 5.2)

try this code, I have not tested in Alamofire(5.2)

let baseUrl = "your URL"
let fullUrl = baseUrl + strUrl
var headers : HTTPHeaders = HTTPHeaders(["Content-type" : "multipart/form-data"])
if let header = header{
headers = header
}

guard let url = try? URLRequest(url: fullUrl, method: .post, headers: headers) else {return}
AF.upload(multipartFormData: { (multipartData) in

for i in 0 ..< arrImage.count{
if let imageData = arrImage[i].pngData(){
let mediaName = "media\(i + 1)"
multipartData.append(imageData, withName:mediaName, fileName: "\(Date().timeIntervalSince1970).jpg", mimeType: "file")
}
}
for (key, value) in parameter {
multipartData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
}, to: url).responseJSON(queue: .main, options: .allowFragments) { (response) in
switch response.result{
case .success(let value):
print("Json: \(value)")
case .failure(let error):
print("Error: \(error.localizedDescription)")
}
}.uploadProgress { (progress) in
print("Progress: \(progress.fractionCompleted)")
}

How to upload array or list of files (images) with Alamofire

@maxwel's answer worked just one modification just add file format in fileName "hunter_picture.jpg". Added .jpg and it worked

Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append((userId.data(using: String.Encoding.utf8, allowLossyConversion: false))!, withName: "userID")

for (index,image) in self.spottingImages.enumerated() {
if let imageData = UIImageJPEGRepresentation(image, 1) {
multipartFormData.append(imageData, withName: "hunter_picture[\(index)]", fileName: "hunter_picture.jpg", mimeType: "image/jpeg") }
}
},
to: url,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
print(upload)
case .failure(let encodingError):
print(encodingError)}
})

Swift 3 Alamofire 4 Upload array of images with parameters

So the error was from the server side, that had a very small size limit for images and that's why they weren't saving. I updated the compression for the JPEG images from

if  let imageData = UIImageJPEGRepresentation(image, 1)

to

if  let imageData = UIImageJPEGRepresentation(image, 0.6)

and now it's working fine.

Thank you @Sneak for your links.

Upload multiple images in swift using Alamofire

Swift 3
Just use "[]" with image upload param to make it array of images.

Alamofire.upload(multipartFormData: { multipartFormData in
// import image to request
for imageData in imagesData {
multipartFormData.append(imageData, withName: "\(imageParamName)[]", fileName: "\(Date().timeIntervalSince1970).jpeg", mimeType: "image/jpeg")
}
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}, to: urlString,

encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in

}
case .failure(let error):
print(error)
}

})


Related Topics



Leave a reply



Submit