1

I was trying to upload multiple images in a single batch where I convert images into base64 strings, append them into a json and send. But when I append more than 3 or 4 images server gets null for json for some reason. I think it is because base64 strings are huge in length.

My requirement is like this, I want to upload multiple images which are under one upload id and each and every image should have its own tags.

My json was like this

{ 
    "upload_id":[{
                   "tag1.tag2": "base64 string of image 1"
                 },
                 {
                   "tag3.tag4": "base64 string of image 2"
                 }]
} 

and this is the code i used to make the json and upload

// Images are saved in the documents directory, image paths are saved in imgPathsArr array and tags are saved in tagsArr.

var uploadDict = [String: Any]()
var imgDictArr = [[String: Any]]()

for (indx,imgPath) in imgPathsArr.enumerated(){
    do{
        let imgData = try Data(contentsOf: URL(fileURLWithPath: imgPath))
        let base64Str = imgData.base64EncodedString(options: .init(rawValue: 0))
        let imageDict = [tagsArr[index]:base64Str]
        imgDictArr.append(imageDict)
    }catch let error{
        print(error.localizedDescription)
    }        
}

uploadDict[nic!] = imgDictArr

Alamofire.request("url", method: .post, parameters: uploadDict, encoding: JSONEncoding.default, headers: nil).response { (response) in

    //things after getting response 
}

Any possible way to get my work done. Any help would be highly appreciated.

Hanushka Suren
  • 723
  • 3
  • 10
  • 32
  • 3
    Do not send it using base64. Use multipart upload. Better create a compress single file and upload it in once. Even you can you a background session for it. – Dheeraj D Apr 11 '18 at 12:56

1 Answers1

1

Multipart is better than sending it in pure binary-to-text like base64. In the multipart request, clients construct request to send files and data over to an HTTP Server. It is commonly used by browsers and HTTP clients to upload files to the server.

There is a link below which goes into Multipart a bit more in detail:

https://stackoverflow.com/a/19712083/7461562

deoKasuhal
  • 2,867
  • 20
  • 27
Super_Simon
  • 1,250
  • 8
  • 25
  • 1
    @Al.G.IMHO, this is indeed an answer and it is a correct one especially because it provides useful hints how to solve the problem. It turns out, that a working solution may become more complex. The answer does not, however, provide a "copy&paste" solution - which IMHO should not be a criteria for a sufficient answer because these solutions are usually not sufficient anyway for more complex ones. – CouchDeveloper Apr 17 '18 at 06:37