代码之家  ›  专栏  ›  技术社区  ›  Shoeb Siddique

通过Swift 3和Alamofire 4 | iOS | Swift上传带有JSON和自定义标题的照片/文件

  •  8
  • Shoeb Siddique  · 技术社区  · 7 年前

    我需要使用图像文件和JSON调用多部分请求。

    我已经试过了,但仍然会出错。

     // define parameters
      let parameters = [
        "hometown": "yalikavak",
        "living": "istanbul"
      ]
    
    Alamofire.upload(multipartFormData: { multipartFormData in
        if let imageData = UIImageJPEGRepresentation(image, 1) {
          multipartFormData.append(imageData, withName: "file", fileName: "file.png", mimeType: "image/png")
        }
    
        for (key, value) in parameters {
          multipartFormData.append((value?.data(using: .utf8))!, withName: key)
        }}, to: "upload_url", method: .post, headers: ["Authorization": "auth_token"],
            encodingCompletion: { encodingResult in
              switch encodingResult {
              case .success(let upload, _, _):
                upload.response { [weak self] response in
                  guard let strongSelf = self else {
                    return
                  }
                  debugPrint(response)
                }
              case .failure(let encodingError):
                print("error:\(encodingError)")
              }
      })
    }
    

    3 回复  |  直到 7 年前
        1
  •  4
  •   Virajkumar Patel    7 年前

    在一个请求中尝试多个上传图像的代码,该代码已经可以工作了。

         // For Pass Valid Parameters & number of Images in Array in Image Upload Function
         var dicImgData : NSMutableDictionary? = NSMutableDictionary()
    
         if let img = UIImage(named: "Your Image") {
             if let data:Data = UIImagePNGRepresentation(img) {
                 var imageData : NSData = data
                 dicImgData! .setObject(imageData, forKey: "data" as NSCopying)
                 dicImgData! .setObject("file", forKey: "name" as NSCopying)
                 dicImgData! .setObject("file.png", forKey: "fileName" as NSCopying)
                 dicImgData! .setObject("image/png", forKey: "type" as NSCopying)
    
                 let dicParameter = [
                     "hometown": "yalikavak",
                     "living": "istanbul"
                 ]
    
                 self.uploadImage(url: "Your URL", Parameter: dicParameter, Images: [dicImgData])
             }
        }
    

    上传功能

        func uploadImage (url: String, Parameter param : NSDictionary, Images arrImage: NSArray) -> Void
        {
            var requestURL : String! = url
            let headers = [
                "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
                "Accept": "application/json",
                ]
    
            print("---------------------")
            print("Request URL :- \(requestURL)")
            print("---------------------")
    
            Alamofire.upload(multipartFormData: { (data) in
    
                for (key, value) in param {
                    data.append((value as! String).data(using: .utf8)!, withName: key as! String)
                }
    
                for imageInfo in arrImage
                {
                    var dicInfo : NSDictionary! = imageInfo as! NSDictionary
                    data.append(dicInfo["data"] as! Data, withName: dicInfo["name"] as! String, fileName: dicInfo["fileName"] as! String, mimeType: dicInfo["type"] as! String)
                    dicInfo = nil
                }
    
            }, to: requestURL, method: .post , headers:nil, encodingCompletion: { (encodeResult) in
                switch encodeResult {
                case .success(let upload, _, _):
    
                    upload.responseJSON(completionHandler: { (response) in
    
                        switch response.result
                        {
                        case .success(let responseJSON):
                            guard let dicResponse = responseJSON as? NSDictionary else{
                                return
                            }
    
                            print("Response : \((dicResponse))")
    
                        case .failure(let error):
    
                            print(error)
    
                            break
                        }
                    })
                case .failure(let error):
                    print(error)
                    break
                }
            })
        }
    
        2
  •  2
  •   Saranjith    7 年前

    状态代码400表示您传递给api的json没有遵循api文档。例如,如果他们想要一个键“name”,而你根本没有得到这样的键。

    似乎你没有提到任何内容类型

    添加这些代码行以确保响应和请求的格式正确

    Alamofire.request(.GET, "your url", parameters: ["foo": "bar"])
             .validate(statusCode: 200..<300)
             .validate(contentType: ["application/json"])
             .response { (_, _, _, error) in
                      println(error)
             }
    

    Accept头告诉服务器客户端在 发送请求。

    如果你能提供更多信息,我们可以提供进一步帮助。

        3
  •  1
  •   Dávid Pásztor    7 年前

    import Foundation
    import Alamofire
    class WebServiceHandler: AnyObject {
    
        func uploadWithAlamofire(Parameters params : [NSObject : AnyObject]?,ImageParameters imgparams :  [NSObject : AnyObject]?,VideoParameters vidoparam :  [NSObject : AnyObject]?,Action action : NSString, success: @escaping (AnyObject) -> Void, failure: @escaping (AnyObject) -> Void)
        {
            var base_url = "http://benzatineinfotech.com/webservice/finder/index.php/Web_api/"
            base_url.append(action as String)
    
            Alamofire.upload(multipartFormData: { multipartFormData in
                if imgparams != nil{
                    for (key, value) in imgparams! {
                        if let imageData = UIImageJPEGRepresentation(value as! UIImage, 1) {
                            multipartFormData.append(imageData, withName: key as! String, fileName: "\(NSDate().timeIntervalSince1970 * 1000)).jpg", mimeType: "image/jpg")
                        }
                    }
                }
                if vidoparam != nil{
                    for (key, value) in vidoparam! {
                        multipartFormData.append(value as! URL , withName: key as! String, fileName: "\(NSDate().timeIntervalSince1970 * 1000).mp4", mimeType: "application/octet-stream")
                    }
                }
                if params != nil
                {
                    for (key, value) in params! {
                        multipartFormData.append((value as! String).data(using: .utf8)!, withName: key as! String)
                    }
    
                } }, to: base_url, method: .post, headers: nil,
                     encodingCompletion: { encodingResult in
                        switch encodingResult {
                        case .success(let upload, _, _):
                            upload.uploadProgress { progress in
                                print(progress.fractionCompleted)
                            }
                            upload.response { [weak self] response in
                                guard self != nil else {
                                    return
                                }
                                let responseString = String(data: response.data!, encoding: String.Encoding.utf8)
                                return success(responseString as AnyObject)
    
                            }
                        case .failure(let encodingError):
                            print("error:\(encodingError)")
                            return failure(encodingError as AnyObject)
                        }
            })
        }
        func convertToDictionary(text: String) -> [String: Any]? {
            if let data = text.data(using: .utf8) {
                do {
                    return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
                } catch {
                    print(error.localizedDescription)
                }
            }
            return nil
        }
    }
    

    用法:

    self.webservice.uploadWithAlamofire(Parameters: dict_params as [NSObject : AnyObject], ImageParameters: imgparam as [NSObject : AnyObject], VideoParameters:  videoparam as [NSObject : AnyObject], Action: "write_message", success: { (success) in
            print(success)
    }) { (error) in
            print(error)
    }