How to list the names of files successfully uploaded? - php

I have a a form which contains a file input and upload button
<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='stopImageUpload(this);' class='imageuploadform' >
<p class='imagef1_upload_form' align='center'><label>Image File: <input name='fileImage' type='file' class='fileImage' /></label>
<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>
</p>
<p><span class='list></span></p>
</form>
Now what I want is that if an image has finished uploading, at the bottom of this form (in the span tag 'list') I want the name(s) of the file that have been uploaded. So when a file is successfully uploaded, then it should display the name of the uploaded file. If a second file is successfully upoaded, then it displays the name of the uploaded second file below the name of the first file.
Is this possible in Javascript?
I have uploading of files all sorted out in php and javascript. Below is javascript function after uploading is complete:
function stopImageUpload(success) {
var result = '';
if (success == 1) {
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
};
return true;
}​
This function is in the same page in the fomr but not in the same page as the uploading script but in the uploading script does call on this function using this javascript code below:
<script language="javascript" type="text/javascript">window.top.window.stopImageUpload(<?php echo $result; ?>);</script>
Below is part of the uploading php code where it uploads the file into the server:
move_uploaded_file($_FILES["fileImage"]["tmp_name"],"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;

Your PHP callback should contain the name of the file currently uploaded, or even an array of all uploaded files.
Then, in the stopImageUpload function, read that second parameter and manipulate #list accordinly (update/add html):
<ul id="list"></ul>
function stopImageUpload(success, filename) {
var result;
if (success == 1)
result = '<li class="msg">The file '+filename+' was uploaded successfully!</li>';
else
result = '<li class="emsg">There was an error during upload of file '+filename+'!</li>';
$('#list').append(result);
return true;
}​

Related

Customer uploads different files to one product with different responses from the site

I am using Opencart 1.5.6 and I have two file upload options for one product. One option is an image and the other is a video. I am setting it up to show a preview of the image once they upload.
In catalog/controller/product/product.php under public function upload() I have changed the code as follows to get a thumbnail image and change the success message:
if (!$json && is_uploaded_file($this->request->files['file']['tmp_name']) && file_exists($this->request->files['file']['tmp_name'])) {
$file = basename($filename) . '.' . md5(mt_rand());
// Hide the uploaded file name so people can not link to it directly.
$json['file'] = $this->encryption->encrypt($file);
//ADDED THIS//
$json['thumb'] = $file;
move_uploaded_file($this->request->files['file']['tmp_name'], DIR_DOWNLOAD . $file);
//CHANGED THIS//
$json['success'] = 'The file "' . basename($filename) . '" has been uploaded.';
}
In catalog/view/theme/<mytheme>/template/product/product.tpl I added a div to place the thumbnail in.
<div class="image-area" style="width:300px;height:215px;overflow:hidden;"></div>
Then at the bottom of the product.tpl I made the following change:
<script type="text/javascript"><!--
new AjaxUpload('#button-option-<?php echo $option['product_option_id']; ?>', {
action: 'index.php?route=product/product/upload',
name: 'file',
autoSubmit: true,
responseType: 'json',
onSubmit: function(file, extension) {
$('#button-option-<?php echo $option['product_option_id']; ?>').after('<img src="catalog/view/theme/default/image/loading.gif" class="loading" style="padding-left: 5px;" />');
$('#button-option-<?php echo $option['product_option_id']; ?>').attr('disabled', true);
},
onComplete: function(file, json) {
$('#button-option-<?php echo $option['product_option_id']; ?>').attr('disabled', false);
$('.error').remove();
if (json['success']) {
alert(json['success']);
$('input[name=\'option[<?php echo $option['product_option_id']; ?>]\']').attr('value', json['file']);
}
if (json['error']) {
$('#option-<?php echo $option['product_option_id']; ?>').after('<span class="error">' + json['error'] + '</span>');
}
$('.loading').remove();
<!-- ADDED THIS -->
<!-- Show thumb -->
$(".image-area").html('<img src="download/' + json.thumb + '"/><h6>Image File Preview</h6>');
}
});
//--></script>
All of the above code works perfectly. When I upload the image it gives a success message that includes the file name and it displays the image in the div that I created for it.
The problem is that when I click the upload button for the video upload and upload an image (I haven't limited this to just upload just video files). It will replace the image preview area from the previous upload with whatever I uploaded to the video area. I know that this is because it accesses the same code.
The HTML for both buttons on the front end is as follows:
<label style="max-width:200px;"> Upload File:</label>
<input id="button-option-227" class="button " type="button" value="Upload File">
<input type="hidden" value="2J5cqKQ0z8g96DwobtxqZfWcS925rtBIl0U3cSmI06f3EEs9E-6m9k_22emKdPkcR9QjwK3zDdW1I7S4vqQZew,," name="option[227]">
<label style="max-width:200px;">Upload Video:</label>
<input id="button-option-228" class="button " type="button" value="Upload File">
<input type="hidden" value="sbG0MtD_ebRQBeO73zWTNWhK8Y1rf-O6L3422G7D6FNjxlo0FM3GhoC5a1HiZk9DYgX5hjUPj5yxogQ67LrK-A,," name="option[228]">
Question:
How can I separate this code so that only the image upload option will access it and the video upload option will access a different code and respond differently?
If there are any other solutions I would appreciate any tips.
I change the following code:
<!-- Show thumb -->
$(".image-area").html('<img src="download/' + json.thumb + '"/><h6>Image File Preview</h6>');
To:
<!-- Show thumb -->
<?php if ($option['product_option_id'] == <<IMAGE OPTION ID>>) { ?>
$(".image-area").html('<img src="download/' + json.thumb + '"/><h6>Image File Preview</h6>');
<?php } ?>
Thanks for the tip shadyyx!

Uploading file via PHP in form

(beginner)
I'm having trouble uploading my file. I see the filename being posted to the database, but the file is not being posted to the images folder. It seems as though nothing is happening. Here is my following code, please advise me what I need to change:
<?php
//the $art variable gets posted to a database eventually
$art = mysql_real_escape_string(stripslashes($_FILES["art"]["name"]));
$art_ext = pathinfo($art, PATHINFO_EXTENSION);
$art = md5($art).".".$art_ext;
if($art!=""){
move_uploaded_file($art, "images/".$art );
}
?>
<script type="text/javascript">
$(function(){
image_upload = {
UpdatePreview: function(obj){
// if IE < 10 doesn't support FileReader
if(!window.FileReader){
// don't know how to proceed to assign src to image tag
} else {
var reader = new FileReader();
var target = null;
reader.onload = function(e) {
target = e.target || e.srcElement;
$("#imageupload").attr("src", target.result);
};
reader.readAsDataURL(obj.files[0]);
}
}
};
});
</script>
<form action="new.php" method="post" enctype="multipart/form-data">
<input type='file' name='art' id="file" onchange='image_upload.UpdatePreview(this)' value="Upload" accept="image/gif,image/jpeg,image/png"/>
</p>
<p>upload a image! (.gif, .jpg, .png formats allowed. 5MB max)</p>
<img id="imageupload" src="1x1.png" alt="test" />
<input type="submit" class="smallbtn4" style="cursor:pointer;" value="post"/>
</form>
Here's the format for move_uploaded_file():
$path = 'images/';
move_uploaded_file($_FILES['art']['tmp_name'], $path.basename($_FILES['art']['name']));
when using move_uploaded_files() your destination path should also include the name of the file....right now your destination path is:
images/
it should be:
images/nameOfImg.ext
Hope this helps!
EDIT:
After seeing the comment by #enhzflep, you should also hash the name of the file and create your filename string before using it in move_uploaded_file();

ajax form data serialization failed

I have a HTML with a form in it like this:
<html>
<head>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
</head>
<body>
<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform">
Your Photo: <input id="thefile" type="file" name="photo" size="25" />
<input type="button" name="submit" value="Submit" onclick="submitform();"/>
</form>
</body>
<script>
function submitform()
{
data = $('*').serialize();
$.post(
'http://localhost/banksoal/1.0.0/accept-file.php',
data
);
}
</script>
</html>
and the .php script like this:
<?php
//if they DID upload a file...
if($_FILES['photo']['name'])
{
print_r($_FILES['photo']);
$message = 'default message';
//if no errors...
if(!$_FILES['photo']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = 'd:\\' . '--test-- '.basename($_FILES['photo']['name']); //rename file
if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
else
{
$valid_file = true;
}
//if the file has passed the test
if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], $new_file_name);
$message = 'Congratulations! Your file was accepted.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
}
}
var_dump($message);
?>
The problem:
in the submitform() function, in the script tag at the line:
data = $('*').serialize();
why I get empty result?
What is wrong with the code?
Thank you
change this
data = $('*').serialize();
to
data = $('theform').serialize();
and change this
<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform">
to
<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform" name ="theform">
Give thsi a try as mentioned here: http://api.jquery.com/serialize/
$('form').submit(function() {
console.log($(this).serialize());
return false;
});
You can also use
echo json_encode($data);
http://php.net/manual/en/function.json-encode.php
You cannot upload files using Ajax, if you MUST upload files in an AJAX-like way you can use hidden iframes, set the target attribute equal to the iframe and grab the iframe's content to know whether the request has failed or not
This is what i usually do for this purpose, create a hidden iframe that will be the target to the form, something like this:
<iframe name='formTarget' src='#' style='display:none;' onload='processResult(this);'></iframe>
and in processResult you can fetch the iframe's content by:
$(results).html();
This way when the iframe is loaded it will automatically trigger the function to inform the request is complete

uploadprogress extension : uploadprogress_get_info always returning null

i want to add a progress bar to my upload code
so i've installed uploadprogress extension ( actually i've downgraded my wamp server to wamp 2.0 as this one already has the extension but new versions seems to have problem with it )
here is my backend code
/////////////////// uploading
<?php
if (isset($_POST['upload'])) {
echo 'UPLOADING . . . <br />';
$location = './uploads';
$new= uniqid().'.'.end(explode('.' , basename($_FILES['mailfile']['name']) ));
if(move_uploaded_file( $_FILES['mailfile']['tmp_name'],"$location/$new"))
echo 'DONE !! ';
else
echo 'error';
}
/////////////// getting upload info
else if(isset($_GET['get_info']))
{
if (function_exists("uploadprogress_get_info")) {
$info = uploadprogress_get_info($_GET['get_info']);
} else {
$info = 'nofunc';
}
var_dump($info);
}
/////////////// upload form
else
{ $uploadID = substr(md5(microtime(true)), 0, 10);
?>
<form enctype="multipart/form-data" action="uploadprogress.php" method="post" >
<input type="text" name="UPLOAD_IDENTIFIER" value="<?php echo $uploadID; ?>" id="uploadIdentifier" />
<input id="file" name="mailfile" type="file" />
<input type="submit" value="Send File" id="btn" name="upload" />
</form>
<?php
}
and this is my front html/jquery code
when file is being uploaded it gets the UPLOAD_IDENTIFIER value from iframe and the sends it to the set() function which is suppose to get the upload progress via ajax calls but it always returns null
<html>
<head>
<script language="javascript" src="../../js/jquery.js"></script>
<script>
var val;
$(function(){
$('#progress_iframe').load(function() {
var ifr = $(this);
$(this)
.contents()
.find('#btn')
.bind('click', function() {
val = ifr.contents().find('#uploadIdentifier').val();
set();
// do stuff
});
});
})
function set() {
$.get('uploadprogress.php' , {get_info : val} , function(data){
data = $.trim(data);
$('#info').html(data) ;
if(data < 100 )
set();
})
}
</script>
</head>
<body>
<div>
<iframe id="progress_iframe" src="uploadprogress.php" frameborder="0"> </iframe>
<span id="info"></span>
</div>
</body>
</html>
so the file is being uploaded without any problem and i've tried a big file but still as the file was being uploaded the uploadprogress_get_info was null
Check if the UploadProgress tmp directory is accessible on the server. Meaning the "uploadprogress.file.filename_template" refers to the right tmp folder in the phpinfo.
You can run the following code to check this.
<div id="status" style="border: 1px black solid;<?php
$templateini = ini_get("uploadprogress.file.filename_template");
$testid = "thisisjustatest";
$template = sprintf($templateini, $testid);
$templateerror = false;
if ($template && $template != $templateini && #touch($template) && file_exists($template)) {
// print '('.$templateini.' is writable. The realpath is ' . str_replace($testid,"%s",realpath($template)) .')';
unlink($template);
} else {
$templateerror = true;
}
if (function_exists("uploadprogress_get_info")) {
if ($templateerror) {
print 'background-color: red;"';
print ">Problem. ";
if ($template == $templateini) {
print "uploadprogress.file.filename_template ($templateini) doesn't have an %s in it for making unique temporary files. Please adjust.<br/>";
} else {
print "$templateini is NOT writable. <br/>Please make sure the directory exists and is writable for the webserver. <br/>
Or adjust the ini setting 'uploadprogress.file.filename_template' to a correct path.";
}
} else {
print 'background-color: green;">The uploadprogress extension is installed and initial checks show everything is good';
}
} else {
?>
background-color: red;">The uploadprogress extension is not installed.
<?php } ?>
</div>
If the above code gives error, point to the correct tmp directory in the php.ini file. The following line was added in the php.ini file for Xampp tmp directory on windows localhost machine. uploadprogress.file.filename_template = C:\xampp\tmp\some_name_%s.txt
Now your code should work.

PHP - Upload picture and display on page

The following code allows me to upload pictures (using a html form) to a directory on my server.
<?php
$target = "http://www.mockcourt.org.uk/user/htdocs/pics/2012/";
$target = $target . basename( $_FILES['uploaded']['name']);
$ok=1;
if (move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
?>
Is there any way to modify it so that it will add the pictures to a html page instead?
Thanks
Well after you upload it, you can use javascript to put it on the html page.
I'm not quite sure what your question is, though
EDIT:
So, html form on your page:
<form action="imageUpload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="jupload();" id="form1" >
<div style="visibility:'hidden';" class="imageholder"> <!-- a gif image to show that the process wasn't finished -->
</div>
<input type="file" name="imgfile" />
<input type="submit" name="uploadButton" class="upbtn" value="Submit" />
</form>
Javascript(JQUERY) code for the upload and image add:
function jupload()
{
$(".imageholder").append('<img src="./images/loading.gif">');
}
function juploadstop(result)
{
if(result==0)
{
$(".imageholder").html("");
}
// the result will be the path to the image
else if(result!=0)
{
$(".imageholder").html("");
// imageplace is the class of the div where you want to add the image
$(".imageplace").append("<img src='"+result+"'>");
}
}
php code:
<?php
$target = "http://www.mockcourt.org.uk/user/htdocs/pics/2012/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
if (move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
$result=$target;
}
else
{
$result=0;
}
?>
<script language="javascript" type="text/javascript">
window.top.window.juploadstop(<?php echo $result; ?>);
</script>
Suppose you have the form in HTML to submit the image.. make the submit button, not a submit button, but just a button.. e.g.
<input type='button' id='submit_form' value='upload' />
and in the javascript, use Ajax to submit the form and Jquery to display it in the web page
$('#submit_form')click(function(){
$.ajax({
type: 'POST',
url: path/phpfile.php,
data: image_input_name
});
//after submitting, get the url of the image form the server
$('#div_to_display_image').html("<img src='path/image_file.jpg' alt='this' />");
});
Hope this helps :-)

Categories