-1

I'm using Swift4, I had uploaded image to server using this code

class func uploadMultipleAdvertisementImage(photos: UIImage, completion: @escaping (_ error: Error?, _ sucess: Bool, _ image_id: Int)-> Void) {

    let url = URLs.uploadImages

    var images = [Data]()
    Alamofire.upload(multipartFormData: { (form: MultipartFormData) in



       if let data = UIImageJPEGRepresentation(photos , 0.5) {
            form.append(data, withName: "images", fileName: "photo.jpeg", mimeType: "image/jpeg")
        }

    }, usingThreshold: SessionManager.multipartFormDataEncodingMemoryThreshold, to: url, method: .post, headers: nil) { (result: SessionManager.MultipartFormDataEncodingResult) in

        switch result {
        case .failure(let error):
            print(error)
            completion(error, false, 0)

        case .success(request: let upload, streamingFromDisk: _, streamFileURL: _):

            upload.uploadProgress(closure: { (progress: Progress) in
                print(progress)
            })
                .responseJSON(completionHandler: { (response: DataResponse<Any>) in

                    switch response.result
                    {
                    case .failure(let error):
                        print(error)
                        completion(error, false, 0)

                    case .success(let value):
                        let json = JSON(value)
                        print(json)
                        if(json["msg"] == "image uploaded successfully") {
                            let image_id = json["image_id"].int ?? 0
                            print("hiiiiiiiiii", image_id)
                            completion(nil, true, image_id)
                        }
                    }

                })
        }

    }
}

it worked successfuly, but I want to upload array of images to the server with name "images". there is any way to upload array of images to server rather than upload one?

picciano
  • 22,341
  • 9
  • 69
  • 82
Al-shimaa Adel
  • 767
  • 1
  • 10
  • 26
  • Possible duplicate of https://stackoverflow.com/questions/42427541/swift-3-alamofire-4-upload-array-of-images-with-parameters – Shabbir Ahmad Apr 17 '18 at 12:31
  • 3
    Possible duplicate of [Upload multiple images in swift using Alamofire](https://stackoverflow.com/questions/41499768/upload-multiple-images-in-swift-using-alamofire) – Nitish Apr 17 '18 at 12:32
  • You can check this answer. https://stackoverflow.com/questions/45685210/multipart-form-data-using-alamofire/49550226#49550226 – kalpesh Apr 17 '18 at 12:35
  • You api must be managed get of image data as an array. if that setting parameter for images for one and that overrite each image with new image come from array. contact your backend developer to manage image array – Nitin Gohel Apr 17 '18 at 13:34
  • @NitinGohel no api managed get of image data as an array. – Al-shimaa Adel Apr 17 '18 at 13:45

3 Answers3

0

Just nothing much need to do. Add your

if let data = UIImageJPEGRepresentation(photos , 0.5) {
            form.append(data, withName: "images", fileName: "photo.jpeg", mimeType: "image/jpeg")
        }

code into For loop, and rest of things AlamoFire will take care.

Pratik Patel
  • 1,393
  • 12
  • 18
0

Suppose you are getting images: [UIImage] in the function as a parameter. Then you just need to append all image's data into multipart form, just update the fileName for each image.

Update your code lines as:

for i in 0..<images.count {
    if let data = UIImageJPEGRepresentation(photos[i], 0.5) {        
        form.append(data, withName: "images", fileName: "photo\(i).jpeg", mimeType: "image/jpeg")
    }
}
Ankit Jayaswal
  • 5,549
  • 3
  • 16
  • 36
0

To tell server side that you are sending an array of images or videos, you have to append an open and close square Brackets '[]' to the parameter names. Good luck and happy coding.

public func multipartUpload(_ images: [String: UIImage], videos: [String: Data], params: [String: String], api: API, headers: HTTPHeaders, success: @escaping(Response?) -> Void, fail: @escaping(Error) -> Void) {

    DispatchQueue.main.async {
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
    }

    Alamofire.upload(multipartFormData: { (multipartFormData) in
        for (key, value) in params {
            multipartFormData.append(value.data(using: .utf8)!, withName: key)
        }

        for (name, value) in images {
            multipartFormData.append(UIImageJPEGRepresentation(value, 1)!, withName: "images[]", fileName: name, mimeType: "image/jpeg")
        }

        for (name, value) in videos {
            multipartFormData.append(value, withName: "videos[]", fileName: name, mimeType: "video/mp4")
        }

    }, usingThreshold: UInt64.init(), to: api.path, method: .post, headers: headers, encodingCompletion:{ encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.validate(contentType: ["application/json"]).responseJSON { response in
                DispatchQueue.main.async {
                    UIApplication.shared.isNetworkActivityIndicatorVisible = false
                }

                if let httpStatusCode = response.response?.statusCode, let data = response.data {
                    switch(httpStatusCode) {
                    case 200...300:
                        let mResponse = Response(json: JSON(data), resultCode: httpStatusCode)
                        return success(mResponse)
                    default:
                        let mResponse = Response(json: JSON(data), resultCode: httpStatusCode)
                        return success(mResponse)
                    }
                } else {
                    fail(CustomError(forClientErrorCode: .noDataToReturn))
                }

            }
            upload.uploadProgress(closure: { progress in
                if let aProgressRing = Utility.shared.progressCircle {
                    aProgressRing.startProgress(to: CGFloat(progress.fractionCompleted * 100), duration: 0.1)
                }
                print(progress)
            })
        case .failure(let encodingError):
            print(encodingError)
        }
    })
}