Thinkphp5 Framework for Uploading Pictures Audio and Video Files

  • 2021-12-19 06:18:23
  • OfStack

This article describes the Thinkphp5 framework to achieve picture, audio and video file upload function. Share it for your reference, as follows:

The first is to upload synchronously, the most basic way to upload, and jump to that kind after clicking on the form submission. The front-end code is as follows


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title> Upload a file </title>
</head>
<body>
  <form action="upload" enctype="multipart/form-data" method="post">
    <input type="file" name="image" />
    <br>
    <input type="submit" value=" Upload " />
  </form>
</body>
</html>

Note that enctype here must enctype="multipart/form-data" The scheme must be post. The back-end code directly takes the official website sample code of tp5:


 public function upload(){
  //  Get the form upload file   For example, uploaded 001.jpg
  $file = request()->file('image');
  //  Move to the framework application root directory /public/uploads/  Directory 
  if($file){
    $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
    if($info){
      //  After successful uploading,   Get uploaded information 
      //  Output  jpg
      echo $info->getExtension();
      //  Output  20160820/42a79759f284b767dfcb2a0197904287.jpg
      echo $info->getSaveName();
      //  Output  42a79759f284b767dfcb2a0197904287.jpg
      echo $info->getFilename();
    }else{
      //  Upload failed to get error message 
      echo $file->getError();
    }
  };
 }

Later, I found that I did it simply, so I improved the front-end code, and the front-end code realized file type verification, changing synchronization to ajax asynchronous submission and formdata submission of file data. The background code did not change much, and returned the link of submission file, while the front-end preview can only preview pictures. The modified front-end code is


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title> Upload a file </title>
</head>
<body>
  <form action="uploads1a" id="myform">
    <input type="file" name="image" id="file" />
  </form>
  <div id="test"></div>
  <button id="btn"> Click Upload </button>
  <div>
    <img src="" id="see">
  </div>
  <script type="text/javascript">
  var btn = document.getElementById("btn");
  var file=document.getElementById("file");
  var promise=["png","jpg","jpeg","gif","mp3","mp4","svg"];
  file.onchange=function(){
    var name=file.value;
    var ext=name.substring(name.lastIndexOf(".") + 1).toLowerCase();
    var res=promise.indexOf(ext);
    if (res<0) {
      alert(" The file format is incorrect ");
      document.getElementById("btn").disabled=true;
    }else{
      document.getElementById("btn").disabled=false;
    }
  }
  btn.onclick = function() {
    var val=document.getElementById("file").value;
    if (val.length==0) {
      return;
    }
    var fromData = new FormData(document.forms[0]);
    fromData.append("test", "formdata");
    var oAjax = new XMLHttpRequest();
    oAjax.open('post', "uploadAjax", true);
    oAjax.send(fromData);
    oAjax.onreadystatechange = function() {
      if (oAjax.readyState == 4) {
        if (oAjax.status >= 200 && oAjax.status < 300 || oAjax.status == 304) {
          console.log(oAjax.responseText);
          var data=JSON.parse(oAjax.responseText);
          document.getElementById("see").setAttribute("src","/thinkphp"+data.src);
          document.getElementById("file").value="";
        } else {
          console.log(oAjax.status);
        }
      }
    };
  }
  </script>
</body>
</html>

The back-end code has been improved by 1


public function uploadAjax(){
    //  Get the form upload file   For example, uploaded 001.jpg
  $file = request()->file('image');
  $test=request()->post("test");
  $src=[];// Return to file path 
  //  Move to the framework application root directory /public/uploads/  Directory 
  if($file){
    $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
    if($info){
      //  After successful uploading,   Get uploaded information 
      //  Output  jpg
       $info->getExtension();
      //  Output  20160820/42a79759f284b767dfcb2a0197904287.jpg
       $info->getSaveName();
      //  Output  42a79759f284b767dfcb2a0197904287.jpg
       $info->getFilename();
       $src["src"]=DS.'public'.DS.'uploads'.DS.$info->getSaveName();
    }else{
      //  Upload failed to get error message 
       $file->getError();
    }
  };
    return json_encode($src);
  }

Details, for example, after uploading, the information returned by reporting errors has not been processed.

This is the overall implementation. As a common business scenario, there is still much room for improvement, such as deleting uploaded files or verifying whether files have been uploaded. If uploading cannot be done twice or deleting previously uploaded files. Of course, if the file name is uploaded without processing but with the original name, the original file will be overwritten after uploading.

Readers who are interested in thinkPHP can check the topics of this site: "ThinkPHP Introduction Tutorial", "thinkPHP Template Operation Skills Summary", "ThinkPHP Common Methods Summary", "codeigniter Introduction Tutorial", "CI (CodeIgniter) Framework Advanced Tutorial", "Zend FrameWork Framework Introduction Tutorial" and "PHP Template Technology Summary".

I hope this article is helpful to the PHP programming based on ThinkPHP framework.


Related articles: