【问题标题】:File uploading but name is empty文件上传但名称为空
【发布时间】:2020-02-10 03:32:57
【问题描述】:

我有一个将 PHP 用于我的 API 的 IOS 应用程序。我的文件上传工作正常,但文件名未附加到文件中。我已经在我的应用程序中镜像了其他页面,但它仍然无法正常工作,尽管其他页面工作正常。我可以在服务器上看到文件,但名称是 notes-.jpg。它不是根据代码将 puuid 附加到名称中。我已经在 ViewController 上实现了 MessageKit,但它不起作用(以防万一它有所作为)。下面是我的代码,我觉得我正在大海捞针。代码有点草率(请不要评判)。

func createBodyWithParams(_ parameters: [String: String]?, filePathKey: String?, imageDataKey: Data, boundary: String) -> Data {

    let body = NSMutableData();

    if parameters != nil {
        for (key, value) in parameters! {
            body.appendString("--\(boundary)\r\n")
            body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
            body.appendString("\(value)\r\n")
        }
    }


    // if file is not selected, it will not upload a file to server, because we did not declare a name file
    var filename = ""

    if imageSelected == true {
        filename = "notes-\(puuid).jpg"
        print("name of file", filename)
    }


    let mimetype = "image/jpg"

    body.appendString("--\(boundary)\r\n")
    body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
    body.appendString("Content-Type: \(mimetype)\r\n\r\n")
    body.append(imageDataKey)
    body.appendString("\r\n")

    body.appendString("--\(boundary)--\r\n")

    return body as Data

}

 func uploadImage(_ image: UIImage, completion: @escaping (URL?) -> Void) {
  print("im in upload")
  let avame = user!["ava"]
  let user_id = user!["id"] as! String
  let me = user!["username"] as! String
  let recipientfe = getmessages["recipient"]
  let uuidfe = getmessages["uuid"] as! String
  let recipient = getmessages["username"] as! String
  let rid = String(describing: getmessages["sender_id"]!)
let puuid = UUID().uuidString
    let text = ""

  let url = URL(string: "https://localhost/messagepost.php")!    
  var request = URLRequest(url: url)      
  request.httpMethod = "POST"
    let parameters = ["sender_id": user_id, "uuid": uuidfe, "sender": me, "recipient_id": rid, "recipient": recipient, "puuid": puuid, "text": text]

  let boundary = "Boundary-\(UUID().uuidString)"
  request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

  var data = Data()

  if image != nil {
    data = image.jpegData(compressionQuality: 0.5)!
  }
  request.httpBody = createBodyWithParams(parameters, filePathKey: "file", imageDataKey: data, boundary: boundary)

  URLSession.shared.dataTask(with: request) { data, response, error in

      DispatchQueue.main.async(execute: {
          if error != nil {
              Helper().showAlert(title: "Server Error", message: error!.localizedDescription, in: self)
            print("Server Error")
              return
          }

          do {

              guard let data = data else {
                  Helper().showAlert(title: "Data Error", message: error!.localizedDescription, in: self)
                print("Data Error")
                  return
              }

            let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary

              guard let parsedJSON = json else {
                  return
              }
              if parsedJSON["status"] as! String == "200" {
                let newurl = parsedJSON["path"]
                self.isSendingPhoto = true
                  guard let url = newurl else {
                    return
                  }
                var message = Message(messageuser: self.sender, image: image)
                message.downloadURL = url as? URL

                    self.save(message)
                    self.messagesCollectionView.scrollToBottom()

              } else {

                  if parsedJSON["message"] != nil {
                      let message = parsedJSON["message"] as! String
                      Helper().showAlert(title: "Error", message: message, in: self)
                    print("where am i", parsedJSON["message"] as Any)
                  }

              }

          } catch {
              Helper().showAlert(title: "JSON Error", message: error.localizedDescription, in: self)
            print("where am i 2")
          }

      })
  }.resume()        

}

PHP 上传文件

<?php
if (!empty($_REQUEST["uuid"])) {
    $id = htmlentities($_REQUEST["id"]);
    $recipient = htmlentities($_REQUEST["recipient"]);
    $recipient_id = htmlentities($_REQUEST["recipient_id"]);
    $uuid = htmlentities($_REQUEST["uuid"]);
    $puuid = htmlentities($_REQUEST["puuid"]);
    $text = htmlentities($_REQUEST["text"]);
    $sender = htmlentities($_REQUEST["sender"]);
    $sender_id = htmlentities($_REQUEST["sender_id"]);

if (isset($_FILES['file']) && $_FILES['file']['size'] > 1) {

    $folder = "/home/xxxxx/public_html/notes/" . $uuid;

    // if no posts folder, create it
    if (!file_exists($folder)) {
        mkdir($folder, 0777, true);
    }

    $picture = $folder . "/" . basename($_FILES["file"]["name"]);
            chmod($picture,0777);

    if (move_uploaded_file($_FILES["file"]["tmp_name"], $picture)) {

        $path = "http://localhost/notes/" . $uuid . "/notes-" . $puuid . ".jpg"; 

        $returnArray["message"] = "Post has been made with picture";

        $returnArray["path"] = $path;
        $returnArray["status"] = "200";
    } else {
        $returnArray["message"] = "Post has been made without picture";
        $path = "";
    }
        $result=$access->insertMessage($recipient, $recipient_id, $uuid, $sender,$sender_id, $text, $path);
       // STEP 2.5 If posts are found, append them to $returnArray
       if (!empty($result)) {

        $returnArray["message"] = $result;
       $result = $access->updatebadge($recipient_id);
}
    else {
    $returnArray["message"] = "Couldnt insert". $puuid ."";

    }



 // if data is not passed - show posts except id of the user

}
else {

    $username = htmlentities($_REQUEST["username"]);
    $uuid = htmlentities($_REQUEST["uuid"]);
    $recipient_id = htmlentities($_REQUEST["recipient_id"]);

    $message = $access->conversation($username, $uuid, $recipient_id);

    if (!empty($message)) {
        $returnArray["message"] = $message;
    }

}

}
$access->disconnect();
echo json_encode($returnArray);



?>

【问题讨论】:

  • 你能在服务器中找到上传的文件吗?
  • 你在 print() 中得到文件名?
  • @sayooj 我可以根据时间戳在服务器上找到文件。但是它的名字是notes-.jpg它不是根据代码附加puuid
  • @angel 在 createparams 函数中我得到了文件名,但不在 uploadimage 中
  • 这里有大量的htmlentities() 电话。由于这些都与 HTML 显示转义无关,因此您根本不应该调用此函数。

标签: php json swift file-upload


【解决方案1】:

我想通了。 Swift 中的正文和标头不正确,并且没有发送正确的文件名。

我把body改成:

// web development and MIME Type of passing information to the web server
  let boundary = "Boundary-\(NSUUID().uuidString)"
  request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

  // access / convert image to Data for sending to the server
  var data = Data()

  // if picture has been selected, compress the picture before sending to the server
  if image != nil {
    data = image.jpegData(compressionQuality: 0.5)!
  }

  // building the full body along with the string, text, file parameters
  request.httpBody = Helper().body(with: parameters, filename: "notes-\(puuid).jpg", filePathKey: "file", imageDataKey: data, boundary: boundary) as Data

【讨论】:

    猜你喜欢
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 2015-01-22
    • 1970-01-01
    • 2011-10-04
    • 1970-01-01
    相关资源
    最近更新 更多