简体   繁体   English

Swift 4 Alamofire 分段上传不起作用

[英]Swift 4 Alamofire multipart upload not working

I am using alamofire 4.7 and swift 4我正在使用 alamofire 4.7 和 swift 4

I need to upload image and json to server.我需要将图像和 json 上传到服务器。

I am using the following code below for uploading bu I am getting result failure but data is inserting in server but not getting response, showing some serialization error as something like this我使用下面的代码上传但我得到结果失败但数据插入服务器但没有得到响应,显示一些序列化错误像这样

▿ result : FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
    ▿ failure : AFError
      ▿ responseSerializationFailed : ResponseSerializationFailureReason
  ▿ timeline : Timeline: { "Request Start Time": 548835779.066, "Initial Response Time": 548835779.074, "Request Completed Time": 548835779.127, "Serialization Completed Time": 548835779.127, "Latency": 0.008 secs, "Request Duration": 0.061 secs, "Serialization Duration": 0.000 secs, "Total Duration": 0.061 secs }
    - requestStartTime : 548835779.06617701
    - initialResponseTime : 548835779.07390201
    - requestCompletedTime : 548835779.12704694
    - serializationCompletedTime : 548835779.12748504
    - latency : 0.0077250003814697266
    - requestDuration : 0.060869932174682617
    - serializationDuration : 0.00043809413909912109
    - totalDuration : 0.061308026313781738
  ▿ _metrics : Optional<AnyObject>

================================================================= ================================================== ================

        let auth : String = MitraModal.sharedInstance().getBasicAuthenticationString()
    let headers = ["Authorization": auth, "Content-type": "multipart/form-data"]

    Alamofire.upload(multipartFormData: { (multipartFormData) in

        multipartFormData.append("\(parameters)".data(using: String.Encoding.utf8)!, withName: "data" as String)

        if (!imageArray.isEmpty) {

            for item in imageArray {
                multipartFormData.append(item!, withName: "file", fileName: "image.png", mimeType: "image/png")
            }
        }

    }, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers) { (result) in
        switch result{
        case .success(let upload, _, _):
            upload.responseJSON { response in

                if let JSON = response.result.value
                {
                    print("JSON: \(JSON)")
                    onCompletion?(JSON as? JSON)

                    print("Successfully uploaded")
                }

                if let err = response.error {
                    onError?(err)
                    return
                }
                onCompletion?(nil)
            }
        case .failure(let error):
            print("Error in upload: \(error.localizedDescription)")
            onError?(error)
        }
    }
}

Anyone help ?有人帮忙吗?

As i'm newbie, but Few days ago, i had same problem while uploading image, you must have to accept image by using file on the server side because of your image tag consist withName: "file" .由于我是新手,但几天前,我在上传图片时遇到了同样的问题,您必须在服务器端使用文件来接受图片,因为您的图片标签包含withName: "file"

func AlamofireUploadImages(){

    let url : String = URL_IP+"/ZameenServer/api/addNewProperty.php"
    for img in HOUSEImages{
        let data  = UIImageJPEGRepresentation(img, 0.2)!
        ImagesData.append(data)
    }

    let parameters = [
        "userId"                : "5",
        "unit"                  : "6789"
    ] //Optional for extra parameter

    Alamofire.upload(multipartFormData: { multipartFormData in
        for imageData in self.ImagesData {
            multipartFormData.append(imageData, withName: "file[]", fileName: self.randomString(length: 5)+".jpeg", mimeType: "image/jpeg")
        }
        for (key, value) in parameters {
            multipartFormData.append((value?.data(using: String.Encoding.utf8)!)!, withName: key)
        } //Optional for extra parameters
    },
                     to:url)
    { (result) in

        switch result {
        case .success(let upload, _, _):

            upload.uploadProgress(closure: { (progress) in
                print("Upload Progress: \(progress.fractionCompleted)")
            })

            upload.responseJSON
                {
                    response in
                    print("Response :\(response.result.value)")
            }

        case .failure(let encodingError):
            print("no Error :\(encodingError)")
        }
    }

}

NOTE : As i'm uploading array of images so for uploading multile images use withName: "file[]" or for single image use withName: "file"注意:当我上传图像数组时,上传多张图像使用withName:"file[]"或单个图像使用withName:"file"

Might be it helps you.可能对你有帮助。

Thanks谢谢

   let url = BaseViewController.API_URL + "uploads"
    let image = info[UIImagePickerControllerEditedImage] as? UIImage
    let imgData = UIImageJPEGRepresentation(image!, 0.2)!

    let parameters = [
                            "user_id" : UserDefaults.standard.value(forKey: "userId")!
    ]

    Alamofire.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(imgData, withName: "uload_data",fileName: "file.jpg", mimeType: "image/jpg")
        for (key, value) in parameters {
            multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
        } //Optional for extra parameters
    },
                     to:url)
    { (result) in
        switch result {
        case .success(let upload, _, _):

            upload.uploadProgress(closure: { (progress) in
                print("Upload Progress: \(progress.fractionCompleted)")
            })

            upload.responseJSON { response in

                self.objHudHide()
                print(response.result.value)

                let jsonDict : NSDictionary = response.result.value as! NSDictionary

                print(jsonDict)
                if  jsonDict["status"] as! String == "Success"
                {


                    let detailDict : Dictionary = jsonDict["detail"] as! Dictionary<String,Any>

                    if let getTotalPrice = detailDict["total_price"]
                    {
                        self.lblTotalPrice.text = "$ \(getTotalPrice) + Free Shipping"
                    }

                    if  let getTotalSize = detailDict["total_upload_size"]
                    {
                        self.lblTotalSize.text = "Total Size : \(getTotalSize)"

                    }
                }
               else
                {

                let alertViewController = UIAlertController(title: NSLocalizedString("Alert!", comment: ""), message:"Something Went wrong please try again." , preferredStyle: .alert)
                let okAction = UIAlertAction(title: NSLocalizedString("Ok", comment: ""), style: .default) { (action) -> Void in

                }
                alertViewController.addAction(okAction)
                self.present(alertViewController, animated: true, completion: nil)


        }
            }

        case .failure(let encodingError):
            print(encodingError)
        }
    }

I get the similar issue as well.我也遇到了类似的问题。 This may cause several reasons.这可能会导致多种原因。 In my case that was the error of parameter key of the POST request.在我的情况下,这是 POST 请求的参数键错误。 When you are executing following line当您执行以下行时

multipartFormData.append(item!, withName: "file", fileName: "image.png", mimeType: "image/png")

withName:"file" property refers the parameter key (key of the Json request) for the image of the POST request. withName:"file"属性指的是POST请求图片的参数key(Json请求的key)。 So you can't use whatever the text you want here.所以你不能在这里使用任何你想要的文本。 Please add the correct parameter key of the image that your API is referring instead of "file" .请添加您的 API 引用的图像的正确参数键,而不是"file" Let's say API access the image using "fileImage" as the parameter key.假设 API 使用“fileImage”作为参数键访问图像。 So the above line should be something like this.所以上面的行应该是这样的。

multipartFormData.append(item!, withName: "fileImage", fileName: "image.png", mimeType: "image/png")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM