0

This is how I'm trying to upload an image from my phone gallery using Alamofire...

func uploadTheImg() {
    var i = Int()
        i = 0
        for img in imageArray {
            let url = "http://myUrl…"
            let headers = [ "Content-Type":"application/x-www-form-urlencoded"]

        let imageData: Data = (UIImageJPEGRepresentation(img, 0.6) as Data?)!

        i = i+1
        let parameters: [String: Any]  =
            [
                "seller_id": “263”,
                "is_default": "1",
                "sequence": "\(i)", //This specifies the no.of images picked from the phone gallery
                "image": imageData // This is each of the image in the array.
                "access_token": “4c10c1f41e2cfddb146fd54e871890e2”,
        ]
        Alamofire.upload(multipartFormData: {(multipartFormData) in
            let filePath = NSURL(fileURLWithPath: url)

            multipartFormData.append(imageData, withName: "image", fileName: "\(Date().timeIntervalSince1970).jpeg", mimeType: "image/jpeg")

            for (key, value ) in parameters {
                print(key,value)
                multipartFormData.append(((value) as AnyObject).data(using: String.Encoding.nonLossyASCII.rawValue)!, withName: key)   //CRASHES HERE
            }
        }, to: url)
        { (result) in
            switch result {
            case .success(let upload, , ):

                upload.uploadProgress(closure: { (progress) in
                    UILabel().text = "\((progress.fractionCompleted * 100)) %"
                    print (progress.fractionCompleted * 100)
                })
                upload.responseJSON { response in

                    guard ((response.result.value) != nil) else{
                        print(response.result.error!.localizedDescription)
                        return
                    }
                }
            case .failure(let encodingError):
                print(encodingError)
                break
            }}}}

But in this part... multipartFormData.append(((value) as AnyObject... the for loop prints the keys and values of the "seller_id","is_default","sequence","image" and then it suddenly crashes without printing the access token. Don't know what is causing this crash...

Any help is appreciated..Thanks...

Larme
  • 24,190
  • 6
  • 51
  • 81
  • Same issue as before (https://stackoverflow.com/questions/46661121/issue-with-uploading-an-image-using-alamofirehas-image-as-a-parameter#comment80271218_46661121). `multipartFormData.append(((value) as AnyObject).data(using: String.Encoding.nonLossyASCII.rawValue)!, withName: key) ` will crash because when it hits `"image": imageData`, `imageData` is a `Data` object, so it doesn't responds to `data(using:)` in fact, it doesn't needs it it's already a Data object! And there should be a crash log expliciting clearly that this is the error. – Larme Oct 12 '17 at 09:09
  • Also, since you already do `ultipartFormData.append(imageData,...)` remove `"image": imageData` from the `parameters`. – Larme Oct 12 '17 at 09:17
  • Ok @Larme..so you are saying that even though "image": imageData was a parameter that was supposed to be given, since we have multipartFormData.append(imageData,...), we need not specify imageData as a parameter in the list of Parameters...? –  Oct 12 '17 at 09:39
  • Just remove it because in your code you are adding `imageData` twice, and the second times it's badly done and causes a crash. – Larme Oct 12 '17 at 09:40

2 Answers2

0

You try replace multipartFormData.append(((value) as AnyObject).data(using: String.Encoding.nonLossyASCII.rawValue)!, withName: key) with multiData.append(value.data(using: .utf8)!, withName: key). Hope it helps you

Hai Nguyen
  • 214
  • 1
  • 7
  • @bws Note that in this answer, NSString is not being used. A standard Swift String is being used – Hai Nguyen Oct 12 '17 at 07:48
  • You try convert your parameters to type [String: String]. I believe it will work – Hai Nguyen Oct 12 '17 at 07:51
  • Ok...so you are saaying that instead of [String:Any] in the parameters, it should be [String: String...?] –  Oct 12 '17 at 07:53
  • But doing this also gives an error because the imageData that is passed is of type 'Data'..the error message given is..."Cannot convert value of type 'Data' to expected dictionary value type 'String' " –  Oct 12 '17 at 07:56
  • Please remove image: imageData in your parameters. And do this with your [UIImage] array: for image in arrayImages { if let imageData = UIImageJPEGRepresentation (image, 0.2) { print (imageData) multiData.append (imageData, withName: "image", fileName: "file.jpg", mimeType: "image / jpg") } } } } – Hai Nguyen Oct 12 '17 at 08:28
  • Then convert your parameters to [String: String] and: for (key, value) in parameters { multiData.append (value.data (using: .utf8) !, withName: key) – Hai Nguyen Oct 12 '17 at 08:29
  • Have you finished your work yet? If it seems puzzling I will send you see the code I wrote – Hai Nguyen Oct 12 '17 at 08:29
  • Thanks @Hai Nguyen..it seems it's working fine because I can get the upload progress in the success switch case. But there's a small concern...the control is not going into this block....'upload.responseJSON { response in' Any idea as to why this is happening..? Does it mean anything like the operation has not happened successfully...? –  Oct 12 '17 at 10:11
  • If you have already obtained the upload progress, you have successfully sent multipartFormData to the server. Your problem, you try check your API again – Hai Nguyen Oct 12 '17 at 10:41
  • ok..and does sending multipartFormData to the server mean the image has been uploaded to the server...? –  Oct 12 '17 at 10:45
  • When you print progress.fractionCompleted. That means you have uploaded multipartFormData successfully. As for the problem at "'upload.responseJSON {response in" you try check your API. Do you understand ? – Hai Nguyen Oct 12 '17 at 10:58
  • Ok. @Hai Nguyen –  Oct 12 '17 at 11:09
  • The API seems to be fine @Hai Nguyen ...any idea as to what else could be the issue...? –  Oct 12 '17 at 11:38
0

You can do like this way

let imgData = UIImageJPEGRepresentation(image!, 0.5)!

        Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(imgData, withName: "pictureData",fileName: "file.jpg", mimeType: "image/jpg")}
Raj Oriya
  • 78
  • 4