首页 > 解决方案 > 使用 Swift 在 MySQL 中使用 PHP 将照片存储为 blob

问题描述

我需要使用 swift 在 MySQL 数据库中存储多个字段,但由于某种原因,照片字段不起作用。有什么建议吗?(错误 - 无法将类型“字符串”的值分配给类型“UIImage?”)Swift 连接到 PHP,然后将信息发送到 MySQL。除了照片,一切都完美无缺。我似乎无法弄清楚如何将 SQL 作为 BLOB 文件发送。

@IBOutlet weak var imageView: UIImageView!
@IBAction func takePhoto(_ sender: Any) {
    imagePicker =  UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = .camera

    present(imagePicker, animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    imagePicker.dismiss(animated: true, completion: nil)
    imageView.image = info[.originalImage] as? UIImage
}

@IBOutlet weak var FirstName: UITextField!
@IBOutlet weak var Photo: UIImageView!
@IBOutlet weak var LastName: UITextField!
@IBOutlet weak var ID: UITextField!
@IBOutlet weak var City: UITextField!
@IBAction func submit(_ sender: Any) {
//put the link of the php file here. The php file connects the mysql and swift
let request = NSMutableURLRequest(url: NSURL(string: "https://alpha-rage.co.za/storevalue.php")! as URL)
request.httpMethod = "POST"

let postString = "a=\(FirstName.text!)&b=\(LastName.text!)&c=\(ID.text!)&d=\(City.text!)&e=\(Photo.image!)"

request.httpBody = postString.data(using: String.Encoding.utf8)

let task = URLSession.shared.dataTask(with: request as URLRequest) {
    data, response, error in

    if error != nil {
        print("error=\(String(describing: error))")
        return
    }

    print("response = \(String(describing: response))")

    let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
    print("responseString = \(String(describing: responseString))")
}
task.resume()

let alertController = UIAlertController(title: "Candidate's Name", message:
    "Successfully Added", preferredStyle: UIAlertController.Style.alert)
    alertController.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default,handler: nil))

            self.present(alertController, animated: true, completion: nil)

            FirstName.text = ""
            LastName.text = ""
            ID.text = ""
            City.text = ""
            Photo.image = ""

        }
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
        }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }


    }

标签: phpmysqlswiftswift5

解决方案


如果要将图像以 JSON 格式发送到服务器,则需要做两件事。

首先将其转换为标准图像格式(比如 JPEG)

let jpegData = Photo.image.jpegData(compressionQuality: 0.8)

现在您必须将数据转换为可以放在 JSON 中的格式。最好的方法是将其转换为 base64。

let base64String = jpegData.base64EncodedString()

您可以插入base64String您的 JSON。在服务器端,您可以进行 base64 解码。

所以你的代码如下

// jpegData creation can fail so you need to deal with it. If image is in wrong format or UIImage has no data
guard let jpegData = Photo.image.jpegData(compressionQuality: 0.8) else {return}
let base64String = jpegData.base64EncodedString()
let postString = "a=\(FirstName.text!)&b=\(LastName.text!)&c=\(ID.text!)&d=\(City.text!)&e=\(base64String)"


当然,您可以跳过 base64 编码并将 JPEG 数据作为原始数据发送而无需 JSON。其他字段可以作为 URL 查询参数发送。


推荐阅读