jQuery. Form Upload File Operation

  • 2021-07-16 01:28:11
  • OfStack

Create an test folder

PHP code:


<?php
//var_dump($_FILES['file']);exit;
if(isset($_GET['option']) && $_GET['option']=='delete'){
 @file_put_contents(dirname(__FILE__)."/------------0.txt", $_GET['path']."\r\n",FILE_APPEND);
 unlink($_GET['path']);
 $rs[] = array(
  'success'=>true,
  'info'=>'ok'
 );
 if(file_exists($_GET['path'])){
  $rs[]['success']=false;
  $rs[]['info']=' Not deleted ';
 }
 die(json_encode($rs));
}
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < (1024*1024)))
{
 if ($_FILES["file"]["error"] > 0)
 {
  echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
 }
 else
 {
  if (file_exists("test/" . $_FILES["file"]["name"]))
  {
   $fn = $_FILES["file"]["name"];
  }
  else
  {
   $imgurl = substr($_FILES["file"]["name"], strpos($_FILES["file"]["name"], '.'));
   $imgurl = date("YmdHis",time()).$imgurl;
   move_uploaded_file($_FILES["file"]["tmp_name"],"test/" . $imgurl);
   $fn = "test/" . $imgurl;
  }
 }
 $return_str[] = array(
  'guid'=>date('His',time()),
  'path'=>'test/',
  'fileName'=>$fn,
  'success'=>true
 );
}
else
{
 $return_str[] = array(
  'guid'=>date('His',time()),
  'path'=>'test/',
  'fileName'=>$_FILES["file"]["name"],
  'success'=>false,
  'error'=>$_FILES["file"]["error"]
 );
}
 echo json_encode($return_str); 
?>

HTML code:


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <meta http-equiv="Content-Type" content="multipart/form-data; charset=utf-8" />
 <title> File upload </title>
 <style type="text/css">
  .btn {
   position: relative;
   background-color: blue;
   width: 80px;
   text-align: center;
   font-size: 12px;
   color: white;
   line-height: 30px;
   height: 30px;
   border-radius: 4px;
  }
   .btn:hover {
    cursor: pointer;
   }
   .btn input {
    opacity: 0;
    filter: alpha(opacity=0);
    position: absolute;
    top: 0px;
    left: 0px;
    line-height: 30px;
    height: 30px;
    width: 80px;
   }
  #fileLsit li span {
   margin-left: 10px;
   color: red;
  }
  #fileLsit {
   font-size: 12px;
   list-style-type: none;
  }
 </style>
</head>
<body>
 <div class="btn">
  <span> Add attachments </span>
  <!-- Note here: file  Labels must have name Property, because it is not added name Property, where the file upload cannot be served -->
  <input type="file" id="fileName" name="file" />
 </div>
 <ul id="fileLsit" style="border:1px solid red;">
 </ul>
 <!-- Introduce jquery Class library -->
 <script type="text/javascript" src="js/jquery.js"></script>
 <!-- Introduce jquery.form Plug-ins -->
 <script type="text/javascript" src="js/jquery.form.js"></script>
 <script type="text/javascript">
  jQuery(function () {
   var option =
    {
     type: 'post',
     dataType: 'json', // The data format is json
     resetForm: true,
     beforeSubmit: showRequest,// Events before submission 
     uploadProgress: uploadProgress,// Time being submitted 
     success: showResponse// Events that have been uploaded 
    }
   jQuery('#fileName').wrap(
    '<form method="post" action="test.php" id="myForm2" enctype="multipart/form-data"></form>');
   jQuery('#fileName').change(function () {
    $('#myForm2').ajaxSubmit(option);
   });
  });
  // Delete a file 
  var deleteFile = function (path, guid) {
   console.log(path+'/'+guid);
   jQuery.getJSON('test.php?option=delete', { path: path }, function (reslut) {
    console.log(path+'/'+guid+''+reslut[0].info);
    if (reslut[0].success) {// Delete succeeded 
     jQuery('#' + guid).remove();
     console.log(' Delete succeeded ');
    } else {// Delete failed 
     alert(reslut[0].info);
    }
   });
   console.log('end');
  }
  // Upload in 
  var uploadProgress = function (event, position, total, percentComplete) {
   jQuery('.btn span').text(' Upload in ...');
  }
  // Commencement of Submission 
  function showRequest(formData, jqForm, options) {
   jQuery('.btn span').text(' Start uploading ..');
   var queryString = $.param(formData);
  }
  // Upload complete 
  var showResponse = function (responseText, statusText, xhr, $form) {
   console.log(responseText);
   if (responseText[0].success) {// Return information such as file address and file name after success   Splice rendered to html Inside. 
    var str = '<li id="' + responseText[0].guid + '"><a href="' + responseText[0].fileName + '" target="_blank">' + responseText[0].fileName + '</a><span onclick="deleteFile(\'' + responseText[0].fileName + '\',\'' + responseText[0].guid + '\')" > Delete </span></li>';
    jQuery('#fileLsit').append(str);
   }
   jQuery('.btn span').text(' Upload complete ');
   jQuery('.btn span').text(' Add attachments ');
  }
 </script>
</body>
</html>

The above is the site to introduce you jQuery. Form upload file operation, I hope to help you, if you have any questions welcome to leave a message, this site will reply to you in time!


Related articles: