gpt4 book ai didi

ios - 使用 Swift 通过 PHP 将图像上传到我的服务器

转载 作者:行者123 更新时间:2023-11-30 10:52:59 25 4
gpt4 key购买 nike

我正在使用下面的代码将图像上传到我的服务器,代码发送请求,但始终来自 API 的响应(出现错误)。

在上传图像的同时,该图像的一些信息也会存储在mySql中。

这是我的代码,我使用的是 Xcode 10.1 和 Swift 4.2

 @IBAction func uploadImage(_ sender: Any) {

self.showActivityIndicator()

//Post URL
let url = "https://website.com/folder/include/upload.php"

//Getting text from textFiled!
let name = nameField.text!
let age = ageField.text!

//Call Parameters
let params: Parameters = ["name": name,"age": age]

//Checking image place holder
let image = UIImage(named: "map.png")

//Checking if empty name or age fileds
if name.isEmpty || age.isEmpty{

self.hideActivityIndicator()
myAlert(title: "Error", msg: "Make sure you enter all the required information!")
}

//Checking if image is not selected!!
else if imageView.image == image
{
self.hideActivityIndicator()
myAlert(title: "Error", msg: "Make sure you choose an image!")

}else{

let imageToUpload = self.imageView.image!

Alamofire.upload(multipartFormData:
{
(multipartFormData) in

multipartFormData.append(imageToUpload.jpegData(compressionQuality: 0.75)!, withName: "image", fileName: self.generateBoundaryString(), mimeType: "image/jpeg")
for (key, value) in params
{
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
}, to:url,headers:nil)
{ (result) in
switch result {
case .success(let upload,_,_ ):
upload.uploadProgress(closure: { (progress) in
//Print progress
self.showActivityIndicator()
})
upload.responseJSON
{ response in
//print response.result
if let result = response.result.value {

//Calling response from API
let message = (result as AnyObject).value(forKey: "message") as! String
let status = (result as AnyObject).value(forKey: "status") as! String

//Case Success
if status == "1" {

self.hideActivityIndicator()
print("Your Results are ====> ",result)
self.myAlert(title: "Data Upload", msg: message)


self.imageView.image = UIImage(named: "map.png")
self.nameField.text = ""
self.ageField.text = ""

}else{
self.hideActivityIndicator()
self.myAlert(title: "Error Uploading", msg: message)
}
}

}
case .failure(let encodingError):
print(encodingError)
break
}
}
}
}

}

这是 PHP 文件代码:

<?php

include 'include/connect.php';

//Get Param Data
$name = $_POST["name"];
$age = $_POST["age"];
$xName = mysqli_real_escape_string($conn, $name);
$xAge = mysqli_real_escape_string($conn, $age);



//Results Array
$result = array();

//Image setup
$uploads_dir = 'img';
$tmp_name = $_FILES["image"]["tmp_name"];
$image_name = basename($_FILES["image"]["name"]);
$supported_image = array('gif','jpg','jpeg','png');

$ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));


if(empty($xName) || empty($xAge)|| empty($image_name))
{

// Send some dummy result back to the iOS app
$result["message"] = "Sorry, there was an error uploading your file.";
$result["status"] = "0";
$result["post"] = $_POST;
$result["files"] = $_FILES;


}

if (! in_array($ext, $supported_image))
{

// Send some dummy result back to the iOS app
$result["message"] = "Sorry, Image extension is not Allowed!";
$result["status"] = "0";
$result["post"] = $_POST;
$result["files"] = $_FILES;

}
else
{

$query ="INSERT INTO images (name, age, image) VALUES ('$xName', '$xAge','$image_name')";

if (mysqli_query($conn, $query)) {

move_uploaded_file($tmp_name,"$uploads_dir/$image_name");

// Send some dummy result back to the iOS app
$result["message"] = "Data has been uploaded successfully.";
$result["status"] = "1";
$result["post"] = $_POST;
$result["files"] = $_FILES;

}
}

echo json_encode($result);

?>

API 的响应似乎缺少一些信息,但我正在用所需的信息填充这两个字段,即(姓名和年龄)。

我不知道我缺少什么来完成上传图像及其信息。

谢谢

最佳答案

在按钮点击事件中尝试这个--->

    let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

let addPhotos = UIAlertAction(title: "Choose Photo", style: .default) { (addPhoto) in
self.imgPicker.sourceType = .photoLibrary
self.imgPicker.allowsEditing = false
self.present(self.imgPicker, animated: true, completion: nil)
}

let camera = UIAlertAction(title: "Camera Photo", style: .default) { (CameraPhoto) in
self.imgPicker.sourceType = .camera
self.imgPicker.allowsEditing = false
self.present(self.imgPicker, animated: true, completion: nil)
}

let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (Cencel) in
self.dismiss(animated: true, completion: nil)
}
alert.addAction(addPhotos)
alert.addAction(camera)
alert.addAction(cancel)


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

关于ios - 使用 Swift 通过 PHP 将图像上传到我的服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54268856/

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