alamofire 使用 json 参数上传图片

alamofire upload images with json parameters

我是swift的新手 我想上传 images(从 1 到 4 - 取决于用户)和 video 文件(如果用户愿意)到我的服务器并发送上传时的其他参数(如文本等) 在 android 中,我正在使用改造,这允许我使用 @partmap 来上传我嵌套的 Json 对象。 现在 iOS 我正在使用 Alamofire 但我不能 找到使用 multipart 发送 json 的功能 我该怎么做? 我不想要 base 64 图片 我已经试过了 我的文本内容是嵌套的 明明我要在上传数据时发送json参数 例如:

image 1 = image
post->content = "some text"

正如我在评论中提到的,您需要一个多部分请求。

// Image file which you want to upload.
guard let image = UIImage(named: "YourImage") else { return }


                let imgRep : NSBitmapImageRep = image.representations.first as! NSBitmapImageRep

                let imgData : Data = imgRep.representation(using: .PNG, properties: [:])!


                let cameraFileName    = "some_random_name_img.png"

                let fileUrl = URL(fileURLWithPath: cameraFileName, isDirectory: true)
                do {

                    try imgData.write(to: fileUrl, options: NSData.WritingOptions.atomic)

                    DispatchQueue.main.async {
                        // Stop Camera Session if you are capturing image from camera
                        self.cameraSession.stopRunning()

                        let someParam   = ""
                        let someParam2  = ""


                        let date = Date()
                        let dateString = "\(date)"



                        Alamofire.upload(multipartFormData: { (multipartFormData) in

                        // Add parameters in request 

         multipartFormData.append(cameraFileName.data(using: .utf8)!, withName: "name")

         multipartFormData.append(dateString.data(using: .utf8)!, withName: "startDatetime")

         multipartFormData.append(someParam.data(using: .utf8)!, withName: "userId")

         multipartFormData.append(someParam2.data(using: .utf8)!, withName: "phoneServiceId")

         multipartFormData.append(fileUrl, withName: "file")

                        }, to:"Your_Api_Url.com") // POST Url
                        { (result) in
                            switch result {
                            case .success(let upload, _ , _):

                                upload.uploadProgress(closure: { (progress) in

                                    print("uploding")
                                })

                                upload.responseJSON { response in
                                    print(response)
                                    print("done")






                                }

                            case .failure(let encodingError):
                                print("failed")
                                print(encodingError)

                            }
                        }

                    }

                }
                catch let error as NSError {
                    print("Ooops! Something went wrong: \(error)")
                }