我正在学习"将图像张贴到服务器";,但当我尝试上传多个图像时,它总是报告失败(JSON错误,来自我在iOS设备上的Xcode警报(,似乎错误在PHP方面?但我是新来的,所以任何人都可以帮助我找到任何解决方案。Xcode:
-
httpBody函数
func createBodyWithParameters(参数:[String:Any]?,boundary:String(->NSData{let body=NSMutableData((
if parameters != nil { for (key, value) in parameters! { body.append("--(boundary)rn".data(using: .utf8)!) body.append("Content-Disposition: form-data; name="(key)"rnrn".data(using: .utf8)!) body.append("(value)rn".data(using: .utf8)!) } } for image in images { let filename = "(NSUUID().uuidString).jpg" let imageData = image.jpegData(compressionQuality: 1) let lineOne = "--" + boundary + "rn" body.append(lineOne.data(using: .utf8, allowLossyConversion: false)!) let lineTwo = "Content-Disposition: form-data; name="files"; filename="(filename)"rn" body.append(lineTwo.data(using: .utf8, allowLossyConversion: false)!) let lineThree = "Content-Type: image/jpgrnrn" body.append(lineThree.data(using: .utf8, allowLossyConversion: false)!) body.append(imageData!) let lineFive = "rn" body.append(lineFive.data(using: .utf8, allowLossyConversion: false)!) } let lineSix = "--" + boundary + "--rn" 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
}
多图像上传功能函数上传PostWithMultipleImages(({
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/examplefiles/htdocs/projectExample/posts/'$user_id;
//如果fodler不存在,就创建它if(!file_exists($folder(({mkdir($folder,0777,true(;}其他{$return['older_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;
}
}//前臂
//将详细信息插入数据库$result=$access->insertPost($user_id,$text,$pictures(;
我使用了您的swift代码并成功上传了图像,所以我确信是您的PHP代码出现了一些错误。请确保您返回的json格式正确,如:
echo '{"code" : 200}'