首页 > 解决方案 > Xcode Swift/PHP/SQL 上传多张图片失败

问题描述

我正在学习“将图像发布到服务器”,但是当我尝试上传多个图像时,它总是报告失败(JSON 错误,来自我在 iOS 设备上的 Xcode 警报),似乎错误在 PHP 端?但我是新手,所以任何人都可以帮助我找到任何解决方案。代码:

  1. 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
    

    }

  1. 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
    

    }

  2. 多张图片上传函数 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()
    

    }

  3. 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);

标签: phpiosswift

解决方案


我使用您的 swift 代码并成功上传了图片,所以我确定是您的 PHP 代码有一些错误。请确保您返回的 json 格式正确,例如:

echo '{"code" : 200}'

推荐阅读