php - Xcode Swift/PHP/SQL 上传多张图片失败
问题描述
我正在学习“将图像发布到服务器”,但是当我尝试上传多个图像时,它总是报告失败(JSON 错误,来自我在 iOS 设备上的 Xcode 警报),似乎错误在 PHP 端?但我是新手,所以任何人都可以帮助我找到任何解决方案。代码:
httpBody 函数
func createBodyWithParameters(parameters: [String: Any]?,boundary: String) -> NSData { let body = NSMutableData()
if parameters != nil { for (key, value) in parameters! { body.append("--\(boundary)\r\n".data(using: .utf8)!) body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: .utf8)!) body.append("\(value)\r\n".data(using: .utf8)!) } } for image in images { let filename = "\(NSUUID().uuidString).jpg" let imageData = image.jpegData(compressionQuality: 1) let lineOne = "--" + boundary + "\r\n" body.append(lineOne.data(using: .utf8, allowLossyConversion: false)!) let lineTwo = "Content-Disposition: form-data; name=\"files\"; filename=\"\(filename)\"\r\n" body.append(lineTwo.data(using: .utf8, allowLossyConversion: false)!) let lineThree = "Content-Type: image/jpg\r\n\r\n" body.append(lineThree.data(using: .utf8, allowLossyConversion: false)!) body.append(imageData!) let lineFive = "\r\n" body.append(lineFive.data(using: .utf8, allowLossyConversion: false)!) } let lineSix = "--" + boundary + "--\r\n" body.append(lineSix.data(using: .utf8, allowLossyConversion: false)!) return body
}
http请求函数
func createRequest(parameters: [String : Any] , url : URL) -> URLRequest { var request = URLRequest(url: url) request.httpMethod = "POST" let boundary = "Boundary-\(NSUUID().uuidString)" request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") request.httpBody = createBodyWithParameters(parameters: parameters, boundary: boundary) as Data return request
}
多张图片上传函数 func uploadPostWithMultipleImages() {
guard let id = currentUser?["id"], let text = postTextView.text else { return } // declaring keys and values to be sent to the server let parameters = ["user_id": id, "text": text, "files": images] // declaring URL and request let url = URL(string: "http://localhost/projectExample/uploadPostMultipleImages.php")! let request = createRequest(parameters: parameters, url: url) URLSession.shared.dataTask(with: request) { (data, response, error) in DispatchQueue.main.async { // if error if error != nil { Helper().showAlert(title: "Server Error", message: error!.localizedDescription, in: self) return } // access data / json do { // safe mode of accessing received data from the server guard let data = data else { Helper().showAlert(title: "Data Error", message: error!.localizedDescription, in: self) return } // converting data to JSON let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary // safe mode of accessing / casting JSON guard let parsedJSON = json else { return } // if post is uploaded successfully -> come back to HomeVC, else -> show error message if parsedJSON["status"] as! String == "200" { // post notification in order to update the posts of the user in other viewControllers NotificationCenter.default.post(name: NSNotification.Name(rawValue: "uploadPost"), object: nil) // comeback self.dismiss(animated: true, completion: nil) } else { Helper().showAlert(title: "Error", message: parsedJSON["message"] as! String, in: self) return } // error while accessing data / json } catch { Helper().showAlert(title: "JSON Error", message: error.localizedDescription, in: self) return } } }.resume()
}
PHP上传代码
// generating absolute path to the folder for every user with his unique id
$folder = '/Applications/XAMPP/xamppfiles/htdocs/projectExample/posts/' 。$user_id;
// 如果文件夹不存在则创建文件夹 if (!file_exists($folder)) { mkdir($folder, 0777, true); } else { $return['folder_message'] = '无法创建目录'; }
foreach($_FILES['files']['name'] as $key =>$value) { $file = $_FILES['files']['name'][$key]; $file_tmp = $_FILES['files']['tmp_name'][$key]; // path to the file. Full path of the file $path = $folder . '/' . basename($file); if (move_uploaded_file($file_tmp, $path)) { // creating URL link to the image uploaded $pictures .= 'http://localhost/projectExample/posts/' . $user_id . '/' . $file. " "; $return['pictures'] = $pictures; }
}//foreach
// 将详细信息插入数据库 $result = $access->insertPost($user_id, $text, $pictures);
解决方案
我使用您的 swift 代码并成功上传了图片,所以我确定是您的 PHP 代码有一些错误。请确保您返回的 json 格式正确,例如:
echo '{"code" : 200}'
推荐阅读
- postgresql - Wal-e:无法推送备份 - 权限错误
- webpack - webpack 问题“可下载字体被 sanitizer 拒绝”或“无法解码下载的字体”
- java - java.lang.InternalError:在 PATH 上运行带有 Java14 的 EXE4J .exe 时未初始化平台编码
- kdb - kdb - 如何以动态/快速的方式增加缺少日期的表
- swift - 应用程序在 Xcode 模拟器上运行,但在连接我的手机时显示错误
- c# - C# TimeSpan 给出的结果与预期不同
- django - 如何显示 EmailMultiAlternatives 邮件对象的 html 内容
- java - 如何从 recyclerview 中获取价值并将其相加以获得 android studio 中的总价值
- python - 如何在 SQLAlchment 查询语句中调用函数?
- java - 使用 Java8 使用另一个列表过滤列表