如何在Swift中使用Alamofire上传带参数的图像

时间:2014-10-21 22:52:30

标签: xcode swift upload alamofire

我正在用swift开发一个iPhone应用程序。我使用Alamofire framework来处理http请求。我使用Alamofire.request进行POST,GET等操作:

Alamofire.request(.POST, myURL , parameters: ["a": "1", "b" : "2" ])
        .response { (request, response, data, error) in
}  

我使用Alamofire.upload将图片上传到服务器:

Alamofire.upload(.POST, uploadURL , fileURL)

两者都很完美,但现在我想上传图片并发送一些参数,我的内容类型应为multipart/form-dataAlamofire.upload不接受参数。

还有两个关于swift这个问题的问题,first one没有使用Alamofire(真的,为什么不呢?)和second onemattt(Alamofire开发人员) )引用使用编码参数。

我检查了他的例子,但仍然无法弄清楚如何做到这一点。

任何人都可以帮我解决这个问题吗?

谢谢! :)

6 个答案:

答案 0 :(得分:23)

您可以在代码

下使用 Alamofire 3.0 +
func uploadImageAndData(){
    //parameters
    let gender    = "M"
    let firstName = "firstName"
    let lastName  = "lastName"
    let dob       = "11-Jan-2000"
    let aboutme   = "aboutme"
    let token     = "token"

    var parameters = [String:AnyObject]()
    parameters = ["gender":gender,
                  "firstName":firstName,
                  "dob":dob,
                  "aboutme":about,
                  "token":token,
                  "lastName":lastName]

    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)
        }
    })
}

答案 1 :(得分:4)

SWIFT 2 AlamoFire简单图像上传(REST API)

@amit gupta似乎答案包含很大的开销。 AlamoFire包含简化解决方案的负载。 Alamofire.request方法包含几个简单的重载,可以用来以简单的方式上传。通过使用Alamofire.request(方法开发人员可以摆脱编码开销。

HTTP状态415由于未指定正确的媒体类型而给出。

请检查下面的解决方案。

import UIKit
import Alamofire

class ViewController: UIViewController {

    @IBOutlet var imageView: UIImageView!
    @IBOutlet var btnUpload: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func successDataHandler(responseData:String){

        print ("IMAGE UPLOAD SUCCESSFUL    !!!")

    }

    func failureDataHandler(errorData:String){

        print ("  !!!   IMAGE UPLOAD FAILURE   !!! ")

    }

    @IBAction func actionUpload(sender: AnyObject) {

        let URL = "http://m8coreapibeta.azurewebsites.net/api/cards/SaveImages"

        let postDataProlife:[String:AnyObject] = ["CardId":(dataCardDetail?.userId)!,"ImageType":1,"ImageData":imageView.image!]

        uplaodImageData(URL, postData: postDataProlife, successHandler: successDataHandler, failureHandler: failureDataHandler)
    }

    func uplaodImageData(RequestURL: String,postData:[String:AnyObject]?,successHandler: (String) -> (),failureHandler: (String) -> ()) -> () {

        let headerData:[String : String] = ["Content-Type":"application/json"]

        Alamofire.request(.POST,RequestURL, parameters: postData, encoding: .URLEncodedInURL, headers: headerData).responseString{ response in
            switch response.result {
            case .Success:
                print(response.response?.statusCode)
                successHandler(response.result.value!)
            case .Failure(let error):
                failureHandler("\(error)")
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

答案 2 :(得分:3)

使用swift 3.0的Almaofire

Alamofire.upload(multipartFormData: { multipartFormData in
    var index = 1
    for image in imageArray {
        let imageData: Data = (UIImageJPEGRepresentation(image, 1.0) as Data?)!

        multipartFormData.append(imageData, withName: "home-\(index)", fileName: "home-\(index)", mimeType: "image/jpeg")

        index += 1
    }
    }, with: requestName, encodingCompletion: { result in
        switch result {
        case .success(let upload, _, _):

            upload.responseJSON { response in
                print("Image(s) Uploaded successfully:\(response)")
            }
        case .failure(let encodingError):
            print("encodingError:\(encodingError)")
        }
})

答案 3 :(得分:2)

Swift 4与Alamofire 4

PasswordResetView

答案 4 :(得分:0)

使用swift 2.0的Almaofire 只需复制并粘贴到代码下面。从服务器中获取JSON响应

<html>
  <head>

    <title>Test</title>

  </head>
  <body>
    <p>
      <?php
        $Score = 0;
        //error_reporting(0);
        $Score = $_POST['h1'];
        echo $Score;


      ?>
    </p>
  </body>
</html>

答案 5 :(得分:-2)

要使用编码参数,请创建一个ParameterEncoding变量,为其分配一种编码类型(枚举的情况包括.JSON,.URL),然后将编码函数与NSURLRequest和参数一起使用。此函数返回两个元素的元组,第一个是生成的NSURLRequest,第二个是生成的NSError。

以下是我如何将它用于项目中所需的自定义标题

 var parameterEncoding:ParameterEncoding!
    switch method {
        case .POST, .PUT :
            parameterEncoding = ParameterEncoding.JSON
        default :
            parameterEncoding = ParameterEncoding.URL
    }
    var alamoRequest = Alamofire.Manager.sharedInstance.request(parameterEncoding.encode(mutableURLRequest, parameters: parameters).0)