Ajax Php Image Upload and Save - javascript

I want to upload an image and save it in the uploads folder without refreshing the page. Furthermore, I also want to display the uploaded image on the screen in a div. However, when I run the code, when I try to upload an image, the text continues to say "Image Uploading..." and never finishes to actually upload. Therefore, the image never gets displayed on the page. Additionally, I am having trouble saving my image in the uploads folder, so can someone point me in the right direction? Thank you!
UPDATE: The Ajax POST gets an error each time I try to to upload an image. In fact, the POST request might not even reach my upload.php file. I trie d to alert myself when the request actually reaches upload.php but nothing ever prints out. What may be the potential causes of this?
UPDATE #2: I have included a picture of my file layout. I have the HTML and Javascript in privatecreate.blade.php and the Javascript in upload.php. I want to save the images in uploads folder.
Update #3: I printed out the ajax error and it is "No Input File Specified"
Please bear with my everyone. This is my absolute first time working with php and sql and I am trying my hardest to learn.
HTML:
<div class="container" style="width:700px;">
<br />
<label>Select Image</label>
<input type="file" name="file" id="file" />
<br />
<span id="uploaded_image"></span>
</div>
Javascript:
$(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");
}
else{
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:"upload.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);
}
,error: function(ts)
{
alert("error:" + ts.responseText);
}
});
}
}
});
});
PHP (upload.php):
<?php
//upload.php
$message = "Running Upload.php";
echo "<script type='text/javascript'>alert('$message');</script>";
if($_FILES["file"]["name"] != '')
{
$test = explode('.', $_FILES["file"]["name"]);
$ext = end($test);
$name = rand(100, 999) . '.' . $ext;
$location = 'uploads/' . $name;
move_uploaded_file($_FILES["file"]["tmp_name"], $location);
echo '<img src="'.$location.'" height="150" width="225" class="img-thumbnail" />';
}
?>

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

Related

convert php image upload script to json response

I wrote the script for uploading image in folder say (upload) in my case.
It's working perfectly !
I just want to get response message in json.
I don't know how to use json in scrip and where.
Thanks !
script.js
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$("#message").empty();
$('#loading').show();
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
$('#loading').hide();
$("#message").html(data);
}
});
}));
// Function to preview image after validation
$(function() {
$("#file").change(function() {
$("#message").empty(); // To remove the previous error message
var file = this.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
{
$('#previewing').attr('src','noimage.png');
$("#message").html("<p id='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
return false;
}
else
{
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
$("#file").css("color","green");
$('#image_preview').css("display", "block");
$('#previewing').attr('src', e.target.result);
$('#previewing').attr('width', '250px');
$('#previewing').attr('height', '230px');
};
});
ajax_php_file.php
<?php
if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 100000)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
firstly pass a property in ajax
dataType: "JSON"
next you have to build and array of all the data that your out putting in stead of echo for eg
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
change to
$respons['msg']="<span id='invalid'>***Invalid file Size or Type***<span>";
then use
echo json_encode($respons);
this will pass a json object your client side
once there you can console output your data to see how to access the nested objects

how to request a single file as object

I just start to learn javascirpt, php about 2 days. The problem I face is I already have a x.dcm file under server root, and I already known that path(e.g. http://localhost:8888/....)
My question is how can I simply grab that file from server to use, maybe something like:
var file= 'http://localhost:8888/....'; ////file is not an object
I ask this question because I already known how to use input method:
<input type="file" name="file" id="file">
<script>
$('#file').on('change',function(e){
var file = e.target.file; ///file is an object
});
</script>
but that is not what I want, what I want is to use an existed file rather than input.
So the whole thing is that:
<form id="input" method="post" enctype="multipart/form-data">
<input type="file" id="fileToUpload" name="fileToUpload">
</form>
I firstly make a input to upload some file,then in script
<script>
$("form#input").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: 'segmentation.php',
type: 'POST',
data: formData,
async: false,
success: function (html) {
$('#segbound').html(html);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
</script>
I sent this file(e.g image.dcm) to do something( run a exec) on the server side, then it generates another image(imgproc.dcm) in an expected path(http://localhost:8888/....), and then the next thing is that I what that processed image display on the screen. To do that I need to use a js called cornerstone, and the function in it imageLoader.fileManager.get(file)
which file is that one I what to display.
When I select from input using var file = e.target.file; as I mentioned above, it works perfect, then I check the file type it is a [file object].
But when I want to simply display that 'imgproc.dcm' by using var file= 'http://localhost:8888/....'; the file type is not an object which comes out my question, how can I simply grab that known path image to use as an object.
Or, to improve that, it is possible to get the return (generated imgproc.dcm) directly after it process on server side, and then to use that return(maybe give it an id...do not know) to display (call cornerstone function imageLoader.fileManager.get(file))
On server side, it looks like:
<?php
$target_dir = "/Applications/MAMP/htdocs/dicomread/temp/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (file_exists($target_file)) {
echo "file has already been uploaded.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file)) {
echo "The file ". basename( $_FILES['fileToUpload']['name']). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
$cmd = "/Applications/MAMP/htdocs/dicomread/abc 2>&1";
$Output_fileName = "imgproc.dcm";//$_FILES['fileToUpload']['name'];
exec("$cmd $target_file $Output_fileName);
echo "<br/>done";
?>
Any help would be appreciated.
Use fopen with URL to the file:
$file = fopen("http://localhost:8888/x.dcm", "r");
Refer to this for fopen: http://php.net/manual/en/function.fopen.php

Delete file from a directory with php NO DATABASE

I am stuck on my codes from 2 days now. I have already tried more then 100 tutorials/guide but none of them solve my problem. Mostly guide is for database.
I am using ready made gallery plugin to display images on my website. This gallery does not use database. For that I made admin panel with upload function. Now i am looking for function to delete uploaded photos from admin panel. one pic at a time or multiple option will be more then good.
Right now with this code i am displaying images in Admin Page at main.php which i uploaded before:
<?php
$folder_path = 'gallery-images/'; //image's folder path
$num_files = glob($folder_path . "*.{jpeg,jpg,gif,png,bmp}", GLOB_BRACE);
$folder = opendir($folder_path);
if($num_files > 0)
{
while(false !== ($file = readdir($folder)))
{
$file_path = $folder_path.$file;
$extension = strtolower(pathinfo($file ,PATHINFO_EXTENSION));
if($extension=='jpg' || $extension =='png' || $extension == 'gif' || $extension == 'bmp')
{
?>
<img src="<?php echo $file_path; ?>" height="250" />
<?php
}
}
}
else
{
echo "the folder was empty !";
}
closedir($folder);
?>
And i am trying this delete code in delete.php
<?php
$filename = $_POST['fname'];
$path = $_POST['directory'];
if(file_exists($path."/".$filename)) {
unlink($path."/".$filename); //delete file
}
?>
So i need a function to delete file from server with confirmation and with delete button. Right now file just open with a click. This function will be only for admin, So i think i am safe with delete function as i read in similar topics.
Thanks in Advance.
EDIT 1:
So far this code successfully delete a file from server (Answer from #Jocelyn):
<h3>Delete Now!</h3>
<?php
if(isset($_GET['delete']))
{
unlink(__FILE__);
}
?>
Change this unlink(__FILE__); to unlink("$file_path");
EDIT 2:
Sorry, it does delete file from server but its deleting all the files in that directory.
Is there anyway to delete only one file which i click.
Right now all photos appearing from one link of code, i think thats the problem.
The link is this from which photos are appearing:
<img src="<?php echo $file_path; ?>" height="250" />
A very quickly cobbled together example of how you might achieve your goal using ajax to send the filename to the delete.php script. No doubt that because it's not tested there may well be issues - but it's a starting point.
<?php
/* delete.php */
$img=!empty( $_GET['name'] ) ? $_GET['name'] : false;
$result=false;
if( $img ){
/*
here you would typically check that the path sent via ajax exists
and then use unlink to delete the file before sending a response
to the ajax callback function - the callback would then inform the
user that the file has been deleted ( or not! )
For testing though a simple message will suffice so that files are not deleted unnecessarily!!!
-- uncomment the line below to actually attempt deletion of file.
*/
if( file_exists( $img ) ){
#$result = #unlink( $img );
clearstatcache();
}
echo $result ? 'The file '.$img.' was deleted' : 'The file '.$img.' could not be deleted';
}
?>
<?php
$root='c:/wwwroot';
?>
<!-- /* admin page that lists images */ -->
<html>
<head>
<title>Delete images - no database</title>
<script>
function ajax(imagename,callback){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.status==200 && xhr.readyState==4 ){
callback.call( this, xhr.response );
}
};
xhr.open( 'GET', 'delete.php?name='+imagename, true );
xhr.send();
}
function deleteimage(e){
e.preventDefault();
ajax.call( this, e.target.dataset.path+'/'+e.target.dataset.name, cbdeleteimage );
}
function cbdeleteimage(r){
alert( r );
}
function bindEvents(){
var col=document.querySelectorAll('img.delete');
for( var n in col )if( col[ n ].nodeType==1 ) col[n].addEventListener( 'click', deleteimage, false );
}
document.addEventListener( 'DOMContentLoaded', bindEvents, false );
</script>
</head>
<body>
<?php
$dir = 'gallery-images/'; /* YOUR path */
$dir = $root . '/images/misc/'; /* MY test path */
$files=preg_grep( '#(\.jpg|\.jpeg|\.png|\.bmp|\.gif)#i', glob( $dir . '*.*' ) );
$html=array();
foreach( $files as $file ){
if( $blocal ) $file=str_replace( $root, '', $file ); /* remove MY site root from file names */
$name = pathinfo( $file, PATHINFO_BASENAME );
$path = pathinfo( $file, PATHINFO_DIRNAME );
$html[]="<img class='delete' src='{$file}' data-name='{$name}' data-path='{$path}' />";
}
echo implode( PHP_EOL, $html );
?>
</body>
</html>
So this is the final code which is perfectly fine for noobs like me who stuck with their work:
this is Delete.php to delete only a requested file
<?php
$file = $_GET['delete'];
if(isset($_GET['delete']))
{
unlink("./gallery-images/$file");
header("Location:home.php");
}
?>
This is upload.php to upload file with rename to auto increment value:
<?php
// Upload and Rename File
if (isset($_POST['submit']))
{
$filename = $_FILES["file"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
$file_ext = substr($filename, strripos($filename, '.')); // get file name
$filesize = $_FILES["file"]["size"];
$allowed_file_types = array('.png','.jpg','.jpeg');
$count = count (glob ('gallery-images/*'));
if (in_array($file_ext,$allowed_file_types) && ($filesize < 10000000))
{
// Rename file
$newfilename = ($count + 1) . $file_ext;
if(file_exists("gallery-images/" . $newfilename))
{
// file already exists error
echo "You have already uploaded this file.";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "gallery-images/" . $newfilename);
header("Location: home.php");
exit;
}
}
elseif (empty($file_basename))
{
// file selection error
echo "Please select a file to upload.";
}
elseif ($filesize > 10000000)
{
// file size error
echo "The file you are trying to upload is too large.";
}
else
{
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
unlink($_FILES["file"]["tmp_name"]);
}
}
?>
This is home.php to display image with delete feature:
Upload Form:
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload: <br />
<input type="file" name="file" id="file"><br /><br />
<input type="submit" value="Upload Image" name="submit">
</form>
Display photos from directory:
<?php
$folder_path = 'gallery-images/'; //image's folder path
$num_files = glob($folder_path . "*.{jpeg,jpg,png}", GLOB_BRACE);
$folder = opendir($folder_path);
$file = '$file_path';
if($num_files > 0)
{
while(false !== ($file = readdir($folder)))
{
$file_path = $folder_path.$file;
$extension = strtolower(pathinfo($file ,PATHINFO_EXTENSION));
if($extension=='jpg' || $extension =='png' || $extension == 'jpeg' || $extension == 'bmp')
{
?>
<img src="<?php echo $file_path; ?>" height="175" />
<?php
}
}
}
else
{
echo "the folder was empty !";
}
closedir($folder);
?>
Delete confirmation popup script:
<script>
function deleletconfig(){
var del=confirm("Are you sure you want to delete this record?");
if (del==true){
}
return del;
}
</script>
Hope this will be helpful for learners.
Thanks.

Accessing JSON returned by php script using jquery ajax

Basically my program is a web page with 5 radio buttons to select from. I want my web app to be able to change the picture below the buttons every time a different button is selected.
My problem is coming in the JSON decoding stage after receiving the JSON back from my php scrip that accesses the data in mysql.
Here is my code for my ajax.js file:
$('#selection').change(function() {
var selected_value = $("input[name='kobegreat']:checked").val();
$.ajax( {
url: "kobegreat.php",
data: {"name": selected_value},
type: "GET",
dataType: "json",
success: function(json) {
var $imgEl = $("img");
if( $imgEl.length === 0) {
$imgEl = $(document.createElement("img"));
$imgEl.insertAfter('h3');
$imgEl.attr("width", "300px");
$imgEl.attr("alt", "kobepic");
}
var link = json.link + ".jpg";
$imgEl.attr('src', link);
alert("AJAX was a success");
},
cache: false
});
});
And my php file:
<?php
$db_user = 'test';
$db_pass = 'test1';
if($_SERVER['REQUEST_METHOD'] == "GET") {
$value = filter_input(INPUT_GET, "name");
}
try {
$conn = new PDO('mysql: host=localhost; dbname=kobe', $db_user, $db_pass);
$conn->setAttribute(PDO:: ATTR_ERRMODE, PDO:: ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM greatshots WHERE name = :name');
do_search($stmt, $value);
} catch (PDOException $e) {
echo 'ERROR', $e->getMessage();
}
function do_search ($stmt, $name) {
$stmt->execute(['name'=>$name]);
if($row = $stmt->fetch()) {
$return = $row;
echo json_encode($return);
} else {
echo '<p>No match found</p>;
}
}
?>
Here's my HTML code where I am trying to post the image to.
<h2>Select a Great Kobe Moment.</h2>
<form id="selection" method="get">
<input type="radio" name="kobegreat" value="kobe1" checked/>Kobe1
<input type="radio" name="kobegreat" value="kobe2"/>Kobe2
<input type="radio" name="kobegreat" value="kobe3"/>Kobe3
</form>
<div id="target">
<h3>Great Kobe Moment!</h3>
</div>
And here's is what my database looks like:
greatshots(name, link)
name link
------ --------
kobe1 images/kobe1
kobe2 images/kobe2
kobe3 images/kobe3
Whenever I run the web app right now, the rest of the images on the page disappear and the image I am trying to display won't show up. I get the alert that "AJAX was a success" though, but nothing comes of it other than the alert. Not sure where I am going wrong with this and any help would be awesome.
As mentioned you should parse the JSON response using JSON.parse(json);.
Also, you should specifically target the div element with a simpler setup:
$("#target").append('<img width="300px" src="' + link + '.png"/>');

Can I upload a file using PHP if I ONLY have the absolute path?

What if I have no way of getting the input file:
<input type="file" name="upload" id="upload">
After choosing the file I want to upload, the input field will disappear.
Instead, it will display the absolute path:
C:\users\foo\Desktop\file.zip
C:\fakepath\file.zip
Here's the code I used to get the absolute path:
<script>
$('#upload').on('change',function(){
var filename = document.getElementById("filename").innerHTML;
$.ajax({
type: "POST",
url: "execs/upload.php",
data: { filename: filename},
dataType: "json",
success: function (data) {
alert ("Success")
},
error: function () {
alert ("Failed")
}
});
})
</script>
Will I still be able to upload it in PHP? Most of what I get online is that I will need $_FILES['filename']['tmp_name']. I don't know how I'll get it if I only have the absolute path.
This is the upload.php file:
<?php
$filename = $_POST["filename"]; //C:\users\foo\Desktop\file.zip
$target_dir = "uploads/";
$target_file = $target_dir . $filename;
if(move_uploaded_file($filename, $target_file)){ // $target_file = uploads/file.zip
echo "yes";
}
else echo "no";
?>
When I also checked if the file exists ($filename), it says it does NOT.
Any help would be very much appreciated! Thanks a lot!
You should not use $_POST[] for a file input, use $_FILES[] instead.
For more information check this tutorial.
Please refer to this post:
How to get file name from full path with PHP?
There are two methods:
Using pathinfo.
Using basename.
I prefere pathinfo more.
<?php
$xmlFile = pathinfo('/usr/admin/config/test.xml');
function filePathParts($arg1) {
echo $arg1['dirname'], "\n";
echo $arg1['basename'], "\n";
echo $arg1['extension'], "\n";
echo $arg1['filename'], "\n";
}
filePathParts($xmlFile);
?>
This will return:
/usr/admin/config
test.xml
xml
test
<?php
$path = "/home/httpd/html/index.php";
$file = basename($path); // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
?>
Instead of $_POST use $_FILES as
$filename = $_FILES["upload"];
print_r($filename);
<?php
$uploaddir = "/www/uploads/";
$uploadfile = $uploaddir . basename($_FILES['upload']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['upload']['tmp_name'], $uploadfile)) {
echo "Success.\n";
} else {
echo "Failure.\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
You have $filename = $_POST["filename"]; but change that to:
$filename = $_POST["upload"];
Since you have:
<input type="file" name="upload" id="upload">
So: name="upload"

Categories

Resources