Home  >  Article  >  Backend Development  >  javascript - ajax upload file background uses $_files to accept empty

javascript - ajax upload file background uses $_files to accept empty

不言
不言Original
2018-05-16 09:49:002800browse

javascript code:

<html><head><meta charset="UTF-8">
<style>
img{
   max-width:80%;
   display:block;
}
</style>
</head><body><input id="img" type="file">
<p id="text"></p>
<script>
var 
up=function(o,success,x,file){
   if(typeof success==&#39;function&#39;)
   file=o;
   x=new XMLHttpRequest()
   x.open(&#39;POST&#39;,&#39;http://127.0.0.1/up.php?r=&#39;+Math.random(),1)

   x.onload=function(r){
       r=x.responseText
       if(success)//if r.pid and the twice parameter existing
           return success(r)
   }
   x.send(file)
}
</script>
<script>
img.onchange=function(){
   if(!this.files||!this.files[0])
       return alert(&#39;选取文件出错!&#39;)

   var 
   imgfile=this.files[0]

   if(imgfile.type.indexOf(&#39;image&#39;)!=0)
       return alert(&#39;这不是一个图像或音频!&#39;)
   
   up(imgfile,function(r){
       text.innerHTML=r

   })
}
</script>
</body>
</html>

Backend code:

<?php
  header(&#39;Access-Control-Allow-Origin:*&#39;);
  header("Content-Type:text/json;charset=utf-8");
  echo json_encode($_FILES); 
  ?>

The return data is []

Reply content:

javascript code:

<html><head><meta charset="UTF-8">
<style>
img{
   max-width:80%;
   display:block;
}
</style>
</head><body><input id="img" type="file">
<p id="text"></p>
<script>
var 
up=function(o,success,x,file){
   if(typeof success==&#39;function&#39;)
   file=o;
   x=new XMLHttpRequest()
   x.open(&#39;POST&#39;,&#39;http://127.0.0.1/up.php?r=&#39;+Math.random(),1)

   x.onload=function(r){
       r=x.responseText
       if(success)//if r.pid and the twice parameter existing
           return success(r)
   }
   x.send(file)
}
</script>
<script>
img.onchange=function(){
   if(!this.files||!this.files[0])
       return alert(&#39;选取文件出错!&#39;)

   var 
   imgfile=this.files[0]

   if(imgfile.type.indexOf(&#39;image&#39;)!=0)
       return alert(&#39;这不是一个图像或音频!&#39;)
   
   up(imgfile,function(r){
       text.innerHTML=r

   })
}
</script>
</body>
</html>

Backend code:

 <?php
  header(&#39;Access-Control-Allow-Origin:*&#39;);
  header("Content-Type:text/json;charset=utf-8");
  echo json_encode($_FILES); 
  ?>

The return data is []

Asynchronously upload files, you should use FormData. For example:

var oMyForm = new FormData();
oMyForm.append("file", file);
x.send(oMyForm);


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn