php+ajax File Upload Code Example

  • 2021-12-04 09:41:16
  • OfStack

This article example for everyone to share the php + ajax file upload the specific code, for your reference, the specific content is as follows

html code


<form action="{pboot:form fcode=8}" method="post" id="t" enctype="multipart/form-data">
<input type="file" name='tables_a' id="tables" onchange="abs()">
<input type="hidden" name='tables' id='tables_2'>
<input type="submit" value=" Submit ">
</form>

The project uses pbootCMS, so the address can be ignored
enctype= "multipart/form-data" Because design to file upload must add this attribute to the from form

js code


function abs(){
 var fileArray = document.getElementById('tables').files[0];
 var formData = new FormData();
 formData.append("fileArray", fileArray)
 $.ajax({
  url: "{pboot:httpurl}/api.php/Tables/index",// File to Background Server 
  type: 'POST', // Transfer method 
  data: formData, // Transmitted data 
  dataType : 'json', // Format of data transfer 
  async:false, // This is important 1 Step to prevent duplicate submission      
  cache: false, // Set to false Upload files without caching. 
  contentType: false,// Set to false, Because it is constructed FormData Object , So here it is set to false . 
  processData: false,// Set to false, Because data Value is FormData Object, you don't need to process the data. 
  success: function (responseStr){
   if(responseStr.code != 0){
    alert(' Upload succeeded ');
    $('#tables_2').val('{pboot:httpurl}'+responseStr.data);
   }else{
    alert(' Upload failed ');
   }
  },
  error: function () {
   alert(" Upload error! ");
  }
 });
}

PHP code


public function index()
{
 $name = $_FILES['fileArray']['name'];
 $last = substr($name,strrpos($name,'.'));
 $name = date('YmdHis').rand(10000,99999).$last;
 $address = ROOT_PATH.'/upload/'.$name;
 if(move_uploaded_file($_FILES['fileArray']['tmp_name'],$address)){
  return json(1,'/upload/'.$name);
 }else{
  return json(0);
 }
}

$_ FILES ['fileArray'] ['tmp_name'] is a temporary storage location for the file, so just move it over


Related articles: