在Alamofire中上传图片问题

时间:2018-08-27 15:39:39

标签: ios image alamofire

这是我通过Alamofire将单个图像上传到服务器时的第一次尝试。我已经搜索了它,并且有一种方法可以做到这一点。这就是我将图像从imageview传递到API参数的方式。

 // import Alamofire
func uploadWithAlamofire() {

    let token = UserDefaults.standard.string(forKey: "token")
    let image = UIImage(cgImage: profileImage.image as! CGImage)
    let imageData = UIImagePNGRepresentation(image)
    // define parameters
    let parameters = [
        "token" : token!,
        "name" : nameTxt.text!,
        "about" : descriptionTxt.text!,
        "picture" : imageData as Any
    ] as [String : Any]

    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 as AnyObject).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)")
                }
    })
}

我在这行代码中遇到问题,multipartFormData.append(((value as AnyObject).data(using: .utf8))!, withName: key)编译器显示的错误是:“类型'UInt'没有成员'utf8'`。我该如何解决?这是发送图像的正确方法吗?

2 个答案:

答案 0 :(得分:0)

请尝试从参数中删除图片,然后仅将其分段添加

  • “图片”:将imageData设置为Any(删除此图片)
  • multipartFormData.append(imageData,withName:“ file”,fileName:“ file.png”,mimeType:“ image / png”)(在此处重命名图片参数并插入图片)

答案 1 :(得分:0)

我正在使用此功能及其正常工作。试试看。

func postImageToDB(image : UIImage) {
                           **//enter your url here** 
    let imagePostUrlStr =  "https://myWebsiteName.com/upload_image.php/"

    guard let imageData = UIImagePNGRepresentation(image) else {
      return
    }
    //want to save my image to this directory which is inside root
    **//your params may be different.**
    let params = ["path" : "Brainplow/001243192018125835"]

    Alamofire.upload(multipartFormData: { (multiPartFormData: MultipartFormData) in
      //append path parameter
      for (key, value) in params {
        multiPartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
      }
      multiPartFormData.append(imageData, withName: "fileToUpload", fileName: "testfilename.png", mimeType: "image/png")

    }, to: imagePostUrlStr) { (result: SessionManager.MultipartFormDataEncodingResult) in
      switch result {
      case .success(request: let uploadRequest, _, _ ):


        uploadRequest.uploadProgress(closure: { (progress) in

          print("Upload Progress: \(progress.fractionCompleted)")

        })

        uploadRequest.responseString { response in
          print("printing response string")
          print(response.value as Any)
          print(response)
          print(response.result)

        }

      case .failure(let error):
        print(error.localizedDescription)
      }
    }


  }