简体   繁体   English

文件上传但名称为空

[英]File uploading but name is empty

I have an IOS app that uses PHP for my API.我有一个 IOS 应用程序,它为我的 API 使用 PHP。 My file upload is working fine but the name of the file is not appending to the file.我的文件上传工作正常,但文件名没有附加到文件中。 I've mirrored other pages in my app but it's still not working although others are working fine.我在我的应用程序中镜像了其他页面,但它仍然无法正常工作,尽管其他页面工作正常。 I'm able to see the file on the server, but the name is notes-.jpg.我能够在服务器上看到该文件,但名称是 notes-.jpg。 It's not appending the puuid to the name per the code.它不会根据代码将 puuid 附加到名称。 I've implemented MessageKit on the ViewController that isn't working (just in case it makes a difference).我已经在不工作的 ViewController 上实现了 MessageKit(以防万一它有所作为)。 Here is my code below, I feel like I'm looking for a needle in a haystack.下面是我的代码,我觉得我在大海捞针。 The code is a little sloppy (please don't judge).代码有点马虎(请不要评判)。

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 Upload File 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);



?>

I figured it out.我想到了。 The body and headers in Swift were incorrect and weren't sending the correct file name. Swift 中的正文和标题不正确,并且没有发送正确的文件名。

I changed the body to:我将身体更改为:

// 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM