How to Upload Multiple Images in Multipart Using Alamofire

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)")
}

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)
}

})

Uploading multiple images(with parameters) using multipart form data - Alamofire 5

Try this method to upload multiple images

class func uploadImageWithURL(endPath : String, dictImage : [String:[UIImage]], parameter : [String : Any], header : HTTPHeaders? = nil, success : @escaping ( Any? )->Void, failure : @escaping (Error) -> Void){

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

let url = (try? URLRequest(url: fullUrl, method: .post, headers: headers))!
upload(multipartFormData: { (multipartData) in

for imagesData in dictImage {

for arrimage in imagesData.value{

multipartData.append(arrimage.jpegData(compressionQuality: 0.50)!, withName: imagesData.key, fileName: "\(Date().timeIntervalSince1970).jpg", mimeType: "image/jpeg")
}

}
for (key, value) in parameter {
multipartData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}

}, with: url) { (resultData) in

switch resultData{
case .success(let upload, let streamingFromDisk, let fileURL):

print("File URL : \(String(describing: fileURL))")
print("Streaming From Disk : \(streamingFromDisk)")

upload.uploadProgress(closure: { (progress) in
print("Progress : \(progress.fractionCompleted)")
})
upload.responseJSON(queue: nil, options: .allowFragments, completionHandler: { (response) in
if let value = response.result.value
{
success(value)
}
})
case .failure(let error):
failure(error)
print(error)
}
}
}

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.



Related Topics



Leave a reply



Submit