Skip to content

Instantly share code, notes, and snippets.

@Nekodigi
Created February 27, 2020 12:58
Show Gist options
  • Select an option

  • Save Nekodigi/81d469193d482c7e3cd2ced1dc5f8a86 to your computer and use it in GitHub Desktop.

Select an option

Save Nekodigi/81d469193d482c7e3cd2ced1dc5f8a86 to your computer and use it in GitHub Desktop.
Upload and preview image
<!DOCTYPE html>
<html lang="jp" dir="ltr">
<head>
<meta charset="utf-8">
<title>file upload test</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="up.js"></script>
<script>$(function(){$.get("up.php", {}, function(resp){
show(resp);
});});</script>
</head>
<body>
<form id="my_form">
<input type="file" name="up_file">
<button type="button" onclick="file_upload()">upload</button>
</form>
<p id="status"></p>
<div id="show"></div>
</body>
</html>
function file_upload(){
var formdata = new FormData($('#my_form').get(0));
$.ajax({
url:"up.php",
type:"POST",
data:formdata,
cache:false,
contentType:false,
processData:false,
dataType:"html"
}).done(function(datas, textStatus, jdXHR){
try {
show(datas);
$("#status").text("upload sucsessfuly");
}catch(e){
$("#status").text("upload failed")
}
}).fail(function(jdXHR, textStatus, errorThrown){
$("#status").text("upload failed");
});
}
function show(datas){
var datas = JSON.parse(datas);
var tHTML = "";
Object.keys(datas).forEach(function(key){
tHTML += "<img height=200 src='"+datas[key]+"'>";
});
$("#show").html(tHTML);
}
<?php
if(array_key_exists("up_file", $_FILES)){
$tempfile = $_FILES['up_file']['tmp_name'];
$filename = 'data/' . $_FILES['up_file']['name'];
if(is_uploaded_file($tempfile)){
if(move_uploaded_file($tempfile, $filename)){
echo json_encode(glob("data/*"));
}else{
echo "upload failed";
}
}else{
echo "file is not selected";
}
}else{
echo json_encode(glob("data/*"));
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment