사이트 내 전체검색

 

Upload File without using Form Submit in Ajax PHP & Auto upload withou…

페이지 정보

로빈 조회 248회 2019-01-19 14:27

본문

<!DOCTYPE html>
<html>
 <head>
  <title>Webslesson Tutorial | Upload File without using Form Submit in Ajax PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>



 <body>
  <br /><br />
  <div class="container" style="width:700px;">
  <h2 align="center">Upload File without using Form Submit in Ajax PHP</h2>
  <br />
  <label>Select Image</label>
  <input type="file" name="file" id="file"  style="display: none;"  />
  <br />
<input type="button" value="Browse..." onclick="document.getElementById('file').click();" />
  <span id="uploaded_image"></span>
  </div>



 </body>
</html>

<script>


$(document).ready(function(){


 $(document).on('change', '#file', function(){
  var name = document.getElementById("file").files[0].name;
  var form_data = new FormData();
  var ext = name.split('.').pop().toLowerCase();
  if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1)
  {
  alert("Invalid Image File");
  }
  var oFReader = new FileReader();
  oFReader.readAsDataURL(document.getElementById("file").files[0]);
  var f = document.getElementById("file").files[0];
  var fsize = f.size||f.fileSize;
  if(fsize > 2000000)
  {
  alert("Image File Size is very big");
  }
  else
  {
  form_data.append("file", document.getElementById('file').files[0]);
  $.ajax({
    url:"2.php",
    method:"POST",
    data: form_data,
    contentType: false,
    cache: false,
    processData: false,
    beforeSend:function(){
    $('#uploaded_image').html("<label class='text-success'>Image Uploading...</label>");
    }, 
    success:function(data)
    {
    $('#uploaded_image').html(data);
    }
  });
  }
 });
});
</script>


-------------------------------------------
2.php

<?php
//upload.php
if($_FILES["file"]["name"] != '')
{
 $test = explode('.', $_FILES["file"]["name"]);
 $ext = end($test);
 $name = rand(100, 999) . '.' . $ext;
 $location = './' . $name; 
 move_uploaded_file($_FILES["file"]["tmp_name"], $location);
 echo '<img src="'.$location.'" height="150" width="225" class="img-thumbnail" />';
}
?>

-------------------------------------------
input type=file show only button

<input type="file" id="selectedFile" style="display: none;" />
<input type="button" value="Browse..." onclick="document.getElementById('selectedFile').click();" />
추천0

첨부파일

  • 1.php (2.3K) 0회 다운로드 | DATE : 2019-01-19 14:28:26

댓글목록

등록된 댓글이 없습니다.

게시물 검색

 

회원로그인

접속자집계

오늘
87
어제
673
최대
3,566
전체
2,438,822