javascript - ajax 업로드 파일 백그라운드는 $_files를 사용하여 비어 있음을 허용합니다.

不言
풀어 주다: 2023-03-01 07:34:01
원래의
2769명이 탐색했습니다.

javascript 코드:

<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>
로그인 후 복사

백엔드 코드:

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

반환 데이터는 []

응답 내용:

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>
로그인 후 복사

백엔드 코드:

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

반환되는 데이터는 []

비동기 파일 업로드의 경우 FormData를 사용해야 합니다. 예:

var oMyForm = new FormData();
oMyForm.append("file", file);
x.send(oMyForm);
로그인 후 복사


관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!