1

I am trying to upload multiple images from an array via multipart/form data using the code below.

func uploadImage<T>(resource: Resource<T>, paramName: String, fileName: [String], images: [PLMUploadImage], completionHandler: @escaping (Result<T, PLMError>) -> Void) {   
 let boundary = UUID().uuidString
        var urlRequest = URLRequest(url: resource.url)
        urlRequest.httpMethod = "POST"
        urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
        if let accessToken = resource.accessToken {
            urlRequest.setValue( "\(PLMLOGINAPICONSTANT.BEARER)\(accessToken)", forHTTPHeaderField: PLMLOGINAPICONSTANT.AUTHORIZATION)
        }
        var data = Data()
        for (index, img) in images.enumerated() {
            data.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)
            let fileName = "\(index)" + ".jpg"
            data.append("Content-Disposition: form-data; name=\"\(paramName)\"; filename=\"\(fileName)\"\r\n".data(using: .utf8)!)
            data.append("Content-Type: image/png\r\n\r\n".data(using: .utf8)!)
            data.append(img.image.jpeg(.medium)!)
            data.append("\r\n--\(boundary)--".data(using: .utf8)!)
        }
        let session = URLSession.shared
        session.uploadTask(with: urlRequest, from: data, completionHandler: { responseData, response, error in
            if error == nil {
                let jsonData = try? JSONSerialization.jsonObject(with: responseData!, options: .allowFragments)
                if let json = jsonData as? [String: Any] {
                    PLMLogger.prettyPrint(data:json)
                    let result = try? JSONDecoder().decode(T.self, from: responseData!)
                    if let result = result {
                        DispatchQueue.main.async {
                            completionHandler(.success(result))
                        }
                    } else {
                        DispatchQueue.main.async {
                            completionHandler(.failure(.decodingError))
                        }
                    }
                }
            }
        }).resume()
    }

As you see from the above code, only the last image from the array gets uploaded.

The web API is capable of receiving multiple images.

enter image description here

govind kumar
  • 205
  • 4
  • 12
  • Could it be because `name=\"\(paramName)\"` is the same for all your images? – Larme Aug 19 '21 at 08:12
  • @Larme yes it's the same for all images – govind kumar Aug 19 '21 at 08:13
  • Can the web api receive multiple images at once? "As you see from the above code, only the last image from the array gets uploaded." there is nothing to certify that, no? I don't see why with your code. – Larme Aug 19 '21 at 08:14
  • @Larme yes updated the question. API is capable of receiving multiple images with same param names. – govind kumar Aug 19 '21 at 08:18
  • You are appending `Data` objects to a guy named 'data,' which isn't really an array, no? Sorry, that was a dumb question. – El Tomato Aug 19 '21 at 08:29
  • @ElTomato No it isn't I tried using NSMutableArray didn't work either. – govind kumar Aug 19 '21 at 08:30
  • 1
    @govindkumar, latest value is replace in same parameter key in iOS. And parsing data to same key with different value is very difficult to manage iOS side. So, try to change api in backed side.Parse like this *uploaded_image_0*, *uploaded_image_1*. – Nikunj Gangani Aug 19 '21 at 08:34
  • @NikunjGangani { "uploaded_image": { "image": [file1, file2, file3] } } this is the Post Request format, how do I make the necessary changes to the above code ? – govind kumar Aug 19 '21 at 09:03
  • 1
    @govindkumar You can get idea from postman functionality of code snippet. Which is spot right side upper side. https://ibb.co/kcVY77c – Nikunj Gangani Aug 19 '21 at 09:40
  • @NikunjGangani Tried the above approach no luck. any other approach for sending multiple images using an array via multipart/form data – govind kumar Aug 19 '21 at 12:43
  • Use alamofire. https://stackoverflow.com/questions/41499768/upload-multiple-images-in-swift-using-alamofire – Nikunj Gangani Aug 20 '21 at 05:12

0 Answers0