无法使用Swift上传图片

时间:2018-08-22 15:06:51

标签: json swift http-post nsurlsession

我无法使用swift上传图像。所有其他信息均已正确插入数据库中。此功能提交书的详细信息,但还需要提交图像。如何使用当前的快速代码提交图像?谢谢。

func uploadOrder (completion: @escaping (Bool, Any?, Error?) -> Void) {

    let imageSize: CGSize = (self._book.imageView?.bounds.size)!
    UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
    let context = UIGraphicsGetCurrentContext()
    self._book.imageView?.layer .render(in: context!)
    let myImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    let imageData: NSData = UIImageJPEGRepresentation(myImage, 90)! as NSData
    UIGraphicsEndImageContext()



    let jsonDictionary = NSMutableDictionary()

    guard let url = URL(string: Constants.uploadOrder) else { return }
    var urlRequest = URLRequest(url: url)

    urlRequest.httpMethod = "POST"

    urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")

    if let isbn = self._book.ISBN as String? {
        jsonDictionary.setValue(isbn, forKey:"isbn")
    } else {
         jsonDictionary.setValue("", forKey:"isbn")
    }

    guard let httpBody = try? JSONSerialization.data(withJSONObject: jsonDictionary, options: []) else {
        return
    }
    urlRequest.httpBody = httpBody
    let session = URLSession.shared
    session.dataTask(with: urlRequest) { (data, response, error) in
        if let response = response {
            print("Response", response)
        }
        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                if let status  = (json as AnyObject).value(forKey:"OK") as! Bool? {
                    DispatchQueue.main.async { //GUI thread
                         completion(true, status, nil)
                    }
                }

            } catch  let error {
                print(error.localizedDescription)
                DispatchQueue.main.async { //GUI thread
                    completion(false, nil, error)
                }
            }

        }
        }.resume()

}

1 个答案:

答案 0 :(得分:1)

您可以将图像数据转换为base64

<form action="upload_file.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
...

并将其作为键值添加到您的jsonDictionary

let base64String = imageData!.base64EncodedString(options: .lineLength64Characters)