swift4中Alamofire.upload方法上的图片上传

时间:2018-10-25 12:05:12

标签: swift alamofire image-uploading alamofireimage

我必须使用Alamofire.upload(multipartFormData方法上传图片。 我的代码在下面,但出现这样的错误:

FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error
 Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character
 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))

有人可以告诉我如何解决该问题吗?

func photoSave(_ photoImage : UIImage, type : String)
{
    let urlString = ServerUrl + "document_upload"
    let imageUpload = UIImageJPEGRepresentation(photoImage, 0.5)        
    Alamofire.upload(multipartFormData: { (multipartFormData) in
        let date = Date().timeIntervalSince1970 * 1000
        let fileName = String(date) + "Image.jpg"
        multipartFormData.append(imageUpload!, withName: "image", fileName: fileName, mimeType: "image/jpg")
        multipartFormData.append((self.token.data(using: String.Encoding.utf8, allowLossyConversion: false)!), withName: "token")
        multipartFormData.append((type.data(using: String.Encoding.utf8, allowLossyConversion: false))!, withName: "document_type")
    }, to: urlString, method: .post, encodingCompletion: { (result) in
        switch result {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                print("response11 : ", response.request?.url! as Any,response)
                if response.result.isSuccess
                {
                    let result : AnyObject = response.result.value as AnyObject

                    let success = result["status_message"] as? String

                    if success == "Image Upload Successfully"
                    {
                        DispatchQueue.main.async
                            {                                 
                        }
                    }
                    else
                    {
                        let msg = result["status_message"] as? String
                        DispatchQueue.main.async
                            {
                                let alert = UIAlertController(title: msg, message: "", preferredStyle: .alert)
                                let ok = UIAlertAction(title: "OK", style: .cancel, handler: { Void in
                                })
                                alert.addAction(ok)
                                self.present(alert, animated: true, completion: nil)
                                return
                        }
                    }
                }
                else
                {
                    DispatchQueue.main.async
                        {
                            let alert = UIAlertController(title: "Network Connection Lost", message: "Please try again", preferredStyle: .alert)
                            let ok = UIAlertAction(title: "OK", style: .cancel, handler: { Void in
                            })
                            alert.addAction(ok)
                            self.present(alert, animated: true, completion: nil)
                    }
                    return
                }
            }
        case .failure(let encodingError):
            print(encodingError)
        }
    })
}

2 个答案:

答案 0 :(得分:0)

雨燕4

尝试这种方法(从工作项目中复制粘贴),它应该与您一起使用。

func makeMultipartRequest(endPoint: String, parameters: [String:String], image: UIImage, add_headers: Bool = true, completion: @escaping (_ : Any) -> Void)
{
    var headers: [String:String]? = nil

    if add_headers
    {
        headers =
        [
            "Authorization" : LoginModel.instance.userToken,
            "Content-type": "multipart/form-data",
            "Accept": "application/json"
        ]
    }

    print(headers ?? "no headers")

    Alamofire.upload(multipartFormData: { multipartFormData in

        // image in our API have key : thePhoto

        //
        // resize image first
        //

        var tempImage = image

        // 1) pick the largest of width or height
        // 2) if the largest > 1280 then resize the image
        // (respect to aspect ratio)

        if tempImage.size.width > tempImage.size.height
        {
            if tempImage.size.width > 1280.0
            {
                tempImage = tempImage.resizeWithWidth(width: 1280.0)!
            }
        }
        else
        {
            if tempImage.size.height > 1280.0
            {
                tempImage = tempImage.resizeWithHeight(height: 1280.0)!
            }
        }

        //
        // compress image then appending it to the upload request
        //

        if  let imageData = UIImageJPEGRepresentation(tempImage, 0.7)
        {
            multipartFormData.append(imageData, withName: "thePhoto", fileName: "image.jpeg", mimeType: "image/jpeg")
        }

        // if u don't have parameters, remove the following loop

        for (key, value) in parameters
        {
            multipartFormData.append(value.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!, withName: key)
        }

    }, usingThreshold:UInt64.init(),
       to: endPoint,
       method: .post,
       headers: headers,
       encodingCompletion: { (result) in

        switch result {

        case .success(let upload, _, _):

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

            upload.responseJSON { response in
                print("response : \(response)")
                let backendData = response.result.value!
                let status = Parsing_Manager.instance.parsingRequest(backendData)
                completion(status)
            }

            break

        case .failure(let encodingError):
            print("the error is  : \(encodingError.localizedDescription)")
            completion("failed")

            break

        }
    })

} // end of makeMultipartRequest

祝你好运!

答案 1 :(得分:0)

尝试一下,这对我有用。

func requestAPIWithImage( parameters:  Parameters,url: URLConvertible,Completion: @escaping (_ success: Bool,_ response: AnyObject) -> Void) {
    Alamofire.upload(multipartFormData: { (multipartFormData) in
        print(parameters)
        if Array(parameters.keys).contains(Keys.Image) {
        multipartFormData.append(UIImageJPEGRepresentation((parameters)[Keys.Image] as! UIImage, 1)!, withName: "image", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
        }
        for (key, value) in parameters {
            print(key,value)
            if key != Keys.Image{
            multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
            }
        }
    }, to:url)
    { (result) in
        switch result {
        case .success(let upload, _, _):
            upload.uploadProgress(closure: { (progress) in
            })
            upload.responseJSON { response in
                print(response.result)
                self.getValidDict(result: response.result, completion: { (dict, error) in
                    var dict = dict
                    if dict == nil {
                        dict = NSDictionary.init(dictionary:
                            [kBaseMessageKey: error?.localizedDescription ?? "Some error has been occured",
                             kBaseStatusKey: false])
                    }
                       Completion(true,dict![Keys.result]! as AnyObject)
                })
           }
        case .failure(let encodingError):
            Completion(false,encodingError.localizedDescription as AnyObject)
            break
        }
    }
}