如何使用带有令牌计数器的Alamofire上传图像?

时间:2017-09-06 08:01:00

标签: ios swift file-upload alamofire

我使用Alamofire上传图片,但上传不成功。
我还带了令牌和放大器。服务器的参数 我不知道我是否添加了令牌和放大器参数是否正确。
我使用Alamofire有什么问题?
有什么建议吗? 感谢。

func uploadWithAlamofire(image:UIImage, imageData:Data, imageUrl:URL) {        
    let parameters = ["avatar":imageData]

    Alamofire.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(imageData, withName: user.id, fileName: "\(user.id).jpg", mimeType: "image/jpg")

        for (key, value) in parameters {
            multipartFormData.append(value, withName: key)
        }
    }, to: apiUrl , method: .put, headers: ["Authorization": "Bearer \(token)"],
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.response { [weak self] response in
                        guard self != nil else {
                            return
                        }
                        debugPrint(response)
                    }
                case .failure(let encodingError):
                    print("error:\(encodingError)")
                }
    })
}


func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    photoImage = info[UIImagePickerControllerOriginalImage] as! UIImage
    photoImageView.image = photoImage

    let imageName:String = user.id + ".jpg"
    let documentsPath = NSHomeDirectory().appending("/Documents/Icon/")
    let imagePath = documentsPath.appending(imageName)
    let imageUrl = URL(fileURLWithPath: imagePath)
    print("imageUrl is here:\(imageUrl)")

    let imageData:Data = UIImageJPEGRepresentation(photoImage, 0.001)!

    do {
        try imageData.write(to: imageUrl,options: .atomic)
    } catch let error {
        print(error)
    }

    uploadWithAlamofire(image: photoImage, imageData: imageData, imageUrl: imageUrl)

    self.dismiss(animated: true, completion: nil)
}

2 个答案:

答案 0 :(得分:1)

试试这个:

func uploadImageWith(param params:Dictionary<String,String>,image:UIImage?,handler:@escaping ((Dictionary<String,Any>?,Int) -> Void)) {
    // let keyJson = "json".dataUsingEncoding(NSUTF8StringEncoding)!
    print("Params:\(params)")
    let BASE_URL = "http://"
    Alamofire.upload(
        multipartFormData: { multipartFormData in
            for (key, value) in params {
                multipartFormData.append(value.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: key)
            }

            if image != nil{
                let imgData = UIImageJPEGRepresentation(image!, 0.5)
                if imgData != nil {
                    multipartFormData.append(imgData!, withName: "photo_upload", fileName: "file.png", mimeType: "image/png")
                }
            }
    },
        to: BASE_URL,
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON { response in

                    switch response.result {
                    case .success:
                        if let jsonDict = response.result.value as? Dictionary<String,Any> {
                            print_debug("Json Response: \(jsonDict)") // serialized json response
                            handler(jsonDict,(response.response!.statusCode))
                        }
                        else{
                            handler(nil,(response.response!.statusCode))
                        }
                        if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
                            print("Server Response: \(utf8Text)") // original server data as UTF8 string
                        }
                        break
                    case .failure(let error):
                        handler(nil,(response.response!.statusCode))
                        break
                    }
                }
            case .failure(let encodingError):
                print(encodingError)
            }
    }
    )
}

使用

uploadImageWith(param: ["key":"value"], image: UIImage(name:"icon")) { (response, statusCode) in
    print(response)
}

您必须传递params和image对象,并在闭包中获得作为Dictionary对象的响应。

答案 1 :(得分:0)

使用此功能将图像上传到带有令牌和参数的服务器

func uploadImageAndData(){

var parameters = [String:AnyObject]()
parameters = ["token": token,
              "Name": Name]

let URL = "http://yourserviceurl/"
let image = UIImage(named: "image.png")

Alamofire.upload(.POST, URL, multipartFormData: {
    multipartFormData in

    if let imageData = UIImageJPEGRepresentation(image, 0.6) {
        multipartFormData.appendBodyPart(data: imageData, name: "image", fileName: "file.png", mimeType: "image/png")
    }

    for (key, value) in parameters {
        multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
    }
}, encodingCompletion: {
    encodingResult in

    switch encodingResult {
    case .Success(let upload, _, _):
        print("s")
        upload.responseJSON { 
            response in
            print(response.request)  // original URL request
            print(response.response) // URL response
            print(response.data)     // server data
            print(response.result)   // result of response serialization

            if let JSON = response.result.value {
                print("JSON: \(JSON)")
            }
        }
    case .Failure(let encodingError):
        print(encodingError)
    }
})}

适用于Alamofire 3.0 +