gpt4 book ai didi

php - 如何从 Swift 通过 PHP 将 UIImage 上传到 MySQL?

转载 作者:可可西里 更新时间:2023-11-01 01:40:38 25 4
gpt4 key购买 nike

我有一个应用程序,它通过我编写的一些 PHP 网络服务将一些数据上传到 MySQL 数据库。我已经成功上传了文本数据,但我正在努力尝试上传图片。基本上,用户使用他们的 iPhone 相机拍照,我将其转换为 UIImage,现在想上传它。

我查看了以下资源以寻求帮助,但它们似乎对我不起作用: How to Upload text, pdf, doc, zip file via PHP file upload to MySQL
https://www.youtube.com/watch?v=HqxeyS961Uk (这里的代码不会为我编译,我一个字母一个字母地复制它)
How to post a picture from iPhone app (in Swift) to MySQL database?
Saving image on db mysql through swift
Swift - uploading base64 encoded image to php and displaying the image
Getting a UIImage from MySQL using PHP and jSON

如果可能的话,我想在同一个查询中同时上传图片和文本,因为它们相互关联,而且我的 MySQL 表会为新行分配一个自动编号。

编辑感谢下面的答案。我有点不确定如何实现你们建议的更改。我目前上传文本数据的 Swift 代码是:

let url:NSURL = NSURL(string: "http://www.website.com.au/savenewexpense.php")!
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
var dataDictionary:[String:AnyObject] = ["Date" : strDate, "Staff" : strStaff, "Amount" : dblAmount, "Category" : strCategory]
var data:NSData = NSJSONSerialization.dataWithJSONObject(dataDictionary, options: nil, error: nil)!
request.HTTPBody = data

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

let task:NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in

let response:[String:String] = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! [String:String]
if let result = response["result"] {
if result == "success" {
NSLog("Text Data saved successfully")
if self.SendImageToServer() == true {
NSLog("Image Data saved successfully")
self.SaveSuccessful()
} else {
NSLog("Image Data failed to save")
self.DataFail()
}
} else {
NSLog("Error saving data")
self.DataFail()
}
} else {
NSLog("No response")
self.NoResponse()
}

})

task.resume()
}

我的 PHP 代码是:

    // Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$json = file_get_contents('php://input');
$data = json_decode($json, true);

$stmt = $conn->prepare("INSERT INTO tblExpenses (Date, Staff, Amount, Category) VALUES (?, ?, ?, ?)");
$txtDate = $data['Date'];
$txtStaff = $data['Staff'];
$txtAmount = $data['Amount'];
$txtCategory = $data['Category'];
$stmt->bind_param("ssds", $txtDate, $txtStaff, $txtAmount, $txtCategory);
$stmt->execute();
echo '{"result" : "success"}';


$stmt->close();
$conn->close();

我应该如何在其中实现图像?

谢谢

最佳答案

你所要做的是以设置图像的边界为例,使用代码将图像的 NSDATA 转换为边界值

if let dta = data as? NSData {
bodyData.appendData(String(format:"\r\n--\(boundary)\r\n").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!);
bodyData.appendData(String(format:"Content-Disposition: form-data; name=\"photo\(i)\"; filename=\"image.png\"\r\n").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!);
bodyData.appendData(String(format:"Content-Type: image/png\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!);

bodyData.appendData(dta);
}

这里你要做的是先设置图像名称,然后设置图像数据,首先使用 allowLossyConversion 转换数据,然后将 POST 数据与其他数据一起发送给服务

request.HTTPBody = bodyData

就用这个来发送图片

关于php - 如何从 Swift 通过 PHP 将 UIImage 上传到 MySQL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30158868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com