简体   繁体   English

使用alamofire的多部分/表单数据

[英]multipart/form-data using alamofire

I am making an .post API call and I need to use multipart/form-data. 我正在进行.post API调用,我需要使用multipart / form-data。 I know how to make the call using JSON but I am not familiar with multipart/form-data. 我知道如何使用JSON进行通话,但是我对multipart / form-data并不熟悉。 Using JSON, it is a super easy call. 使用JSON,这是一个超级简单的调用。 Just create a type parameters: 只需创建一个类型参数:

var parameters:Parameters = [:]
parameters["username"] = emailTextField.text!
parameters["password"] = passwordTextField.text!

Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
    //Code here 
}

How would we write this using form data. 我们将如何使用表单数据来编写此代码。 What is the easiest way to do this? 最简单的方法是什么? I don't need to upload any files or anything. 我不需要上传任何文件或任何东西。 All I will ever be doing is making calls with extremely simple items like above. 我将要做的就是用上述极为简单的项目进行通话。 What is the cleanest way to do this using form data. 使用表单数据执行此操作的最干净方法是什么? I am sure this is an extremely basic question and I looked around for help on stack overflow but I only see this being used for more advanced call with files. 我确信这是一个非常基本的问题,我四处寻找有关堆栈溢出的帮助,但我只看到它用于文件的更高级调用。 I just want to know how to do this in the simplest way possible as essentially a replacement for JSON calls. 我只是想知道如何以最简单的方式做到这一点,实质上是替代JSON调用。

Example from the docs: 来自文档的示例:

Alamofire.upload(
    multipartFormData: { multipartFormData in
        multipartFormData.append(unicornImageURL, withName: "unicorn")
        multipartFormData.append(rainbowImageURL, withName: "rainbow")
    },
    to: "https://httpbin.org/post",
    encodingCompletion: { encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                debugPrint(response)
            }
        case .failure(let encodingError):
            print(encodingError)
        }
    }
)

The method's full description (if you need to set headers. Source ): 方法的完整描述(如果需要设置标题,请参见Source ):

/// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls
/// `encodingCompletion` with new `UploadRequest` using the `url`, `method` and `headers`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
/// used for larger payloads such as video content.
///
/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
/// technique was used.
///
/// - parameter multipartFormData:       The closure used to append body parts to the `MultipartFormData`.
/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
///                                      `multipartFormDataEncodingMemoryThreshold` by default.
/// - parameter url:                     The URL.
/// - parameter method:                  The HTTP method. `.post` by default.
/// - parameter headers:                 The HTTP headers. `nil` by default.
/// - parameter encodingCompletion:      The closure called when the `MultipartFormData` encoding is complete.
public func upload(
    multipartFormData: @escaping (MultipartFormData) -> Void,
    usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
    to url: URLConvertible,
    method: HTTPMethod = .post,
    headers: HTTPHeaders? = nil,
    encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?)

In swift 4 and Alamofire 4.7 在Swift 4和Alamofire 4.7中

multipart/form-data request 多部分/表单数据请求

 let email = emailTextField.text!
 let password  = passwordTextField.text!
Alamofire.upload(
            multipartFormData: { multipartFormData in
                multipartFormData.append((email.data(using: String.Encoding.utf8, allowLossyConversion: false))!, withName: "email")
                multipartFormData.append((password.data(using: String.Encoding.utf8, allowLossyConversion: false))!, withName: "password")
 },
            to: url,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseData { response in
                   debugPrint(response)
                    }
                case .failure(let encodingError):
                    print(encodingError)

                }
        }
        )
//MARK: Uploading Multiple Images/File with Parameters
static func uploadMultipleImageWithParamters(aryImage:NSArray,webserviceName:String,postDataDict: String?, completion:@escaping (_ IsSuccess:Bool,_ Response:Any,_ CheckInternet:String) -> Void)
{

    if isInternetAvailable() == false
    {
        let Alert = Customalert()
        Alert.msg(message: msgInternet)
        completion(false,"",objNoInternet)
        return
    }
    let parameters = self.convertToDictionary(text: postDataDict!)
    if parameters == nil{

        let Alert = Customalert()
        Alert.msg(message: "Please Check you Json")
        completion(false,"","")
        return
    }
    Alamofire.upload(
        multipartFormData: { multipartFormData in

            for i in 0..<aryImage.count
            {
                let imageData = UIImagePNGRepresentation(aryImage.object(at: i) as! UIImage)
                multipartFormData.append(imageData!, withName: "Photo\(i)", fileName: "\(Date().timeIntervalSince1970).jpeg", mimeType: "image/jpeg")
            }

            for (key, value) in parameters! {

                if value is String
                {
                     multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
                }
                else if value is NSDictionary
                {
                    let dataExample: Data = NSKeyedArchiver.archivedData(withRootObject: value as! NSDictionary)
                    multipartFormData.append(dataExample, withName: key)

                }else if value is NSArray
                {
                    let objData = NSKeyedArchiver.archivedData(withRootObject: value as! NSArray)
                    multipartFormData.append(objData, withName: key)
                }
            }
    },
        to: baseURL + "\(webserviceName)",
        encodingCompletion: { encodingResult in

            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseString { response in
                    debugPrint(response)
                    print(response)
                    completion(true,response.value!,"")
                    }
                    .uploadProgress { progress in // main queue by default
                        print("Upload Progress: \(progress.fractionCompleted)")
                }
                return
            case .failure(let encodingError):

                debugPrint(encodingError)
            }
    })
}

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

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