简体   繁体   English

为什么我不能在Alamofire中将文件附加为参数值之一?

[英]Why can't I append the file as one of the parameter value in Alamofire?

I want to know why can't I give a file as one of the parameter values and to send the parameter as an upload request in Alamofire. 我想知道为什么不能在Alamofire中将文件作为参数值之一发送给参数,并将其作为上传请求发送。 I tried like this and it works. 我尝试这样,它的工作原理。

let parameters: [String : AnyObject ] = [
        "email" : "abc@gmail.com",
        "password" : "password",
        "full_name": "XXX"]

let image: UIImage? = UIImage(named: "logo.png")

    Alamofire.upload(
        .POST,
        "http://myurl.com/register",
        multipartFormData: { multipartFormData in

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

                if let imageData = UIImageJPEGRepresentation(image!, 1) {
                multipartFormData.appendBodyPart(data: imageData, name: "profile_pic", fileName: "logo.png", mimeType: "image/png")
              }
       },
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .Success(let upload, _, _):
                upload.responseJSON { response in
                    debugPrint(response)
                }
            case .Failure(let encodingError):
                print(encodingError)
            }
        }
    )

Why can't I pass the image as a parameter value? 为什么不能将图像作为参数值传递? And also why should I need to change the image in UIImageJPEGRepresentation . 还有为什么我需要在UIImageJPEGRepresentation更改图像。

If I pass the image as a value without changing the representation, error throws that it is not in NSData format. 如果我在不更改表示形式的情况下将图像作为值传递,则会抛出错误,指出它不是NSData格式。

Note that the request should pass even if there is an image or not, because it is an optional one. 请注意,即使有没有图像,请求也应该通过,因为它是可选的。

As you know, Alamofire just a library to help you to process a NSURLRequest . 如您所知, Alamofire只是一个可帮助您处理NSURLRequest的库。 This is a common way that client can communicate with server via a HTTP request. 这是客户端可以通过HTTP请求与服务器通信的常用方式。 Other platforms (such as Android, Desktop, or Web...) also use this way, too. 其他平台(例如Android,桌面或Web ...)也使用这种方式。 So they must be same format. 因此,它们必须是相同的格式。 The post body only accepts simple data format such as String, Int, or byte[]... It does not know what is UIImage , but NSData . post body仅接受简单的数据格式,例如String,Int或byte []...。它不知道什么是UIImage ,但是不知道NSData NSData is a format of byte[]. NSData是byte []的格式。

So, if you want to upload a text file, or a video, you have to convert it to NSData , too. 因此,如果要上传文本文件或视频,也必须将其转换为NSData

Hope this help. 希望对您有所帮助。

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

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