Progress bar and total so far not showing - javascript

I'm trying to show the progress so far while uploading a file using javascript and php. The code below works and the files get uploaded but the progress bar does not show the progress and the total so far which is the p tag with id loaded_n_total does not show anything. I've tested with small files and files as large as 800MB.
html
<!DOCTYPE html>
<html>
<head>
<script>
function _(el) {
return document.getElementById(el);
}
function uploadFile() {
var file = _("file1").files[0];
//alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("process", progressHandler, false);
ajax.addEventListener("load", completeHander, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "file_upload_parser.php");
ajax.send(formdata);
}
function progressHandler(event) {
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event) {
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event) {
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event) {
_("status").innerHTML = "Upload Aborted";
}
</script>
</head>
<body>
<h2>HTML5 File Upload Progress Bar Tutorial</h2>
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br>
<input type="button" value="Upload File" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width: 300px;"></progress>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
</body>
</html>
php
<?php
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")) {
echo "$fileName upload is complete";
} else {
echo "move_uploaded_file function failed";
}
?>

Change the event from "process" to "progress".
ajax.upload.addEventListener("progress", progressHandler, false);

Related

Fail to upload with PHP and Javascript

Trying to get a file upload program to work but keep getting "move_uploaded_file function failed". I set the permissions on the directory I'm trying to move files to, to 777. I have the file_uploads set to On and post_max_size set to 10G in my php.ini config file. I am also not filtering for any specific file type. But, any file type fails to upload. Please help. Thanks. The code originated from the following online tutorial: http://www.developphp.com/video/JavaScript/File-Upload-Progress-Bar-Meter-Tutorial-Ajax-PHP
html with Javascript
<!DOCTYPE html>
<html>
<head>
<script>
function _(el) {
return document.getElementById(el);
}
function uploadFile() {
var file = _("file1").files[0];
//alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("process", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "file_upload_parser.php");
ajax.send(formdata);
}
function progressHandler(event) {
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event) {
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event) {
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event) {
_("status").innerHTML = "Upload Aborted";
}
</script>
</head>
<body>
<h2>HTML5 File Upload Progress Bar Tutorial</h2>
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br>
<input type="button" value="Upload File" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width: 300px;"></progress>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
</body>
</html>
file_upload_parser.php
<?php
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")) {
echo "$fileName upload is complete";
} else {
echo "move_uploaded_file function failed";
}
?>
i have tested code that you paste here.
one things i found that there is typo mistake for complete handler function
function name is completeHandler and event completeHander is ajax.addEventListener("load", completeHander, false);
after fixing this mistake its running properly on my machine.
can you please fix and try again? #martinb
below is latest code for index.html
<!DOCTYPE html>
<html>
<head>
<script>
function _(el) {
return document.getElementById(el);
}
function uploadFile() {
var file = _("file1").files[0];
//alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("process", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "file_upload_parser.php");
ajax.send(formdata);
}
function progressHandler(event) {
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event) {
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event) {
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event) {
_("status").innerHTML = "Upload Aborted";
}
</script>
</head>
<body>
<h2>HTML5 File Upload Progress Bar Tutorial</h2>
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br>
<input type="button" value="Upload File" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width: 300px;"></progress>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
</body>
</html>
And code for file_upload_parser.php
<?php
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")) {
echo "$fileName upload is complete";
} else {
echo "move_uploaded_file function failed";
}
?>

How to pass form inputs via ajax to other php file

I found this ajax file upload code on github, its working as i wanted but i want to pass more varibales from my form inputs via ajax. i have followed a question on stackoverflow - Send variable from the form (POST) via ajax to another PHP script (GET) . but in my case its not working, i am not getting value via GET on upload.php page.
here is the javascript code
<script>
function _(el){
return document.getElementById(el);
}
function uploadFile(){
var file = _("file1").files[0];
alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
var appid = _("appid").value;
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "modules/upload/demo5/upload.php?appid="+appid);
ajax.send(formdata);
}
function progressHandler(event){
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event){
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
_("status").innerHTML = "Upload Aborted";
}
</script>
this is the form area
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="hidden" name="appid" id="appid" value="EVSA75883664">
<input type="file" name="file1" id="file1"><br>
<input type="button" value="Upload File" onclick="uploadFile(); return false;"><br><br>
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<p id="loaded_n_total"></p>
<h3 id="status"></h3>
</form>
and this is upload.php page code
<?php
include('../../connect.php');
$appid = $_GET['appid'];
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")){
echo "$fileName is Uploaded Successfully. <br><br> <a href='https://www.indian-evisas.org.in/uploadppt.php?appid='.$appid.'>Click here to Proceed to Next Step</a>";
} else {
echo "move_uploaded_file function failed";
}
?>

ajax and php file upload undefined index from inputs

I made a php script today to upload file and also added some inputs for sending information like title and description etc. All was working just fine until i added my javascript with ajax. When i added javascript to the page and submiting the form it no longer gets the information from my input elements. Only from the fileupload input.
Here are the errors im getting:
Notice: Undefined index: format in C:\xampp\htdocs\functions\uploadvideo.php on line 15
Notice: Undefined index: title in C:\xampp\htdocs\functions\uploadvideo.php on line 16
Notice: Undefined index: desc in C:\xampp\htdocs\functions\uploadvideo.php on line 17
I do know that questions about Undefined Index have been asked probably over 1000 times here on stackoverflow but please don't mark this as a duplicate. I know that i get the error because it cannot access the values for my inputs, but why? My guess is that it has something to do with the JavaScript or it may be because i use type="button" instead of type="submit" for my submit button in the form.
So i post my code and hopefully someone here can come up with a solution.
And i tried to explain my problem as good as possible but if it's unclear in any way just let me know
html for upload form
<form action="functions/uploadvideo.php" id="upload_form" method="post" enctype="multipart/form-data">
<label for="title">Title</label><br>
<input type="text" name="title" id="title"><br><br>
<label for="format">Format:</label><br>
<select name="format" id="format">
<option value=".mp4">mp4</option>
<option value=".ogg">ogg</option>
<option value=".webm">webm</option>
</select><br><br>
<label for="desc">Description</label><br>
<textarea name="desc" id="desc"></textarea><br><br>
Select video to upload:
<input type="file" name="file" id="file"><br>
<progress id="progressBar" value="0" max="100" style="width:200px;"></progress><br>
<h3 id="status"></h3><br>
<p id="loaded_n_total"></p><br>
<input type="button" onclick="uploadFile()" value="Upload Video" name="submit">
</form>
JavaScript with AJAX for a progress bar
function _(el) {
return document.getElementById(el);
}
function uploadFile() {
var file = _("file").files[0];
var formdata = new FormData();
formdata.append("file", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "functions/uploadvideo.php");
ajax.send(formdata);
}
function progressHandler(event) {
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" butes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event) {
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event) {
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event) {
_("status").innerHTML = "Upload Aborted";
}
PHP File to upload file
<?php
include('../config/dbconf.php');
// FFMPREG
$name = preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($_FILES["file"]["name"]));
$nameext = preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($_FILES["file"]["name"])) . ".jpg";
$fullvideoname = $_FILES['file']['name'];
$ffmpeg = "c:\\ffmpeg\\bin\\ffmpeg";
$videoFile = $_FILES["file"]["tmp_name"];
$size = "271x170";
$getFromSecond = 5;
$cmd = "$ffmpeg -i $videoFile -an -ss $getFromSecond -s $size ../uploads/thumbnails/$name.jpg";
// SQL VARIABLES
$format = $_POST['format'];
$title = $_POST['title'];
$desc = $_POST['desc'];
$date = time();
// UPLOADED VIDEO
$tmp_name= $_FILES['file']['tmp_name'];
$fileType = $_FILES['file']['type'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$position= strpos($fullvideoname, ".");
$fileextension= substr($fullvideoname, $position + 1);
$fileextension= strtolower($fileextension);
$stmt = $conn->prepare("INSERT INTO videos (name, format, title, description, thumbnail, uploadDate) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssi", $name, $format, $title, $desc, $nameext, $date);
if($stmt->execute()) {
shell_exec($cmd);
if (isset($fullvideoname)) {
$path= '../uploads/videos/';
if (empty($fullvideoname)) {
echo "Please choose a file";
}elseif(!empty($fullvideoname)){
if (($fileextension !== "mp4") && ($fileextension !== "ogg") && ($fileextension !== "webm")){
echo "The file extension must be .mp4, .ogg, or .webm in order to be uploaded";
}elseif(($fileextension == "mp4") || ($fileextension == "ogg") || ($fileextension == "webm")){
if (move_uploaded_file($tmp_name, $path.$fullvideoname)) {
echo "Video Uploaded";
}else{
echo 'Failed to move uploaded file';
}
}
}
}
}else{
echo "Failed";
echo $stmt->error;
}
?>
Your problem is this line:
var formdata = new FormData();
This creates an empty object. You need to tell it to load the contents of the form's data by doing it this way:
var formdata = new FormData(document.getElementById('upload_form'));

Audio File Not Getting Uploaded with ajax

I tried The following code to upload files without pressing submit button. It works for images not for audio or video. When Audio File is uploaded it says undefined index 'file' in the log.
<script>
$('#headerimage').on('change', function() {
var form = document.getElementById('fileupload');
var fileInput = document.getElementById('headerimage');
var file = fileInput.files[0];
var formData = new FormData();
var filename = '';
formData.append('file', file);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
filaname = xhr.responseText;
console.log(xhr.responseText);
}
}
// Add any event handlers here...
xhr.open('POST', form.getAttribute('action'), true);
xhr.send(formData);
});
</script>
<form id="fileupload" method="post" enctype="multipart/form-data" action="upload2.php">
<input type="file" id="headerimage" spellcheck="true" class="typography" name="headerimage">
</form>
<?php
if(!empty($_FILES))
{
$file = $_FILES;
if($file['file']['error'] == 0)
{
$name = explode('.', $file['file']['name']);
$newName = $name[count($name)-1];
if (move_uploaded_file($file['file']['tmp_name'], "uploads/".$newName))
{
echo $newName;
exit;
}
} else {
echo "err";
exit;
}
} else {
echo "errrror";
exit;
}
?>

Javascript progress bar not working with PHP upload form

I've got JS to run with a php upload form.
Everytime I go to upload a file to test this the file DOES upload but the progress bar doesn't work and I get an 'Upload Aborted' error message.
Below is the JS
function _(el) {
return document.getElementById(el);
}
function uploadfile() {
var file = _("file").files[0];
var formdata = new FormData();
formdata.append("file", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHander, false);
ajax.open("POST", "uploader.php");
ajax.send(formdata);
}
function progressHandler(event) {
var percent = (event.loaded / event.total) * 100;
_("progressbar").value = (percent);
}
function completeHandler(event) {
_("status").innerHTML = "Upload Success";
_("progressbar").value = 0;
}
function errorHandler(event) {
_("status").innerHTML = "Upload Failed";
}
function abortHander(event) {
_("status").innerHTML = "Upload Aborted";
}
This script attachs to an HMTL5 <progress> with a default value of 0 and max of 100.
Here is the php file to which I am linking the form to:
<?php
$email = $_POST['email'];
$name = $_POST['name'];
$spc = 'test#email.com';
$message = $_POST['message'];
$size = $_FILES['file']['size'];
$file = $_FILES['file']['tmp_name'];
$filename = $_FILES['file']['name'];
$filetype = $_FILES['file']['type'];
$link = 'http://www.spcink.com/uploads/' . $email . '%7c' . $name;
if(!empty($file)) {
mkdir('../uploads/' . $email . '|' . $name, 0777, true);
move_uploaded_file($file, '../uploads/' . '/'. $email . '|' . $name . '/' . $filename);
mail($spc, 'File upload from:' . $name, $message . $link);
}
?>
I can't seem to figure out what is wrong here. Could some one please look this over and help me out! Thank you!

Categories

Resources