Javascript progress bar not working with PHP upload form - javascript

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!

Related

Progress Bar S3 Bucket - PHP Ajax, Javascript

I'm trying to add a Progress Bar to track the file Upload status of my Form. To upload files I use this Form code:
<form id="contact-form" action="awsUpload.php" method="post" name="frmImage" enctype="multipart/form-data">
<input class="file-input" type="file" style="width:100%;"autocomplete="off" name="ftp" accept="image/*, .zip, .rar, .bzip" onchange="this.form.submit();changeStyle()" class="file-up" id="fileFTP">
</form>
And this PHP code to manage the File Upload request.
<?php
require './aws/aws-autoloader.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
// AWS Info
$bucketName = '***';
$IAM_KEY = '***';
$IAM_SECRET = '***';
// Connect to AWS
try {
// You may need to change the region. It will say in the URL when the bucket is open
// and on creation. us-east-2 is Ohio, us-east-1 is North Virgina
$s3 = S3Client::factory(array(
'credentials' => array(
'key' => $IAM_KEY,
'secret' => $IAM_SECRET
),
'version' => 'latest',
'region' => 'eu-west-1'
));
}
catch (Exception $e) {
die("Error: " . $e->getMessage());
}
// For this, I would generate a unqiue random string for the key name. But you can do whatever.
//$target_file = 'f/' . basename($_FILES["ftp"]['tmp_name']); //ftp is file name at index.php
if (isset($_FILES["ftp"]) && $_FILES["ftp"]["error"] == 0) {
$mimeType = mime_content_type($_FILES["ftp"]["tmp_name"]);
$fileSize = $_FILES["ftp"]["size"];
if (strpos($mimeType, "image") === 0) {
if ($fileSize <= 1000 * 1024 * 1024) { //max image size
$target_dir = "i/";
// $strng = preg_replace("/[\s-]|\#/", "_", basename($_FILES["ftp"]["name"])); //Prima era solo "/[\s-]/"
$target_file = $target_dir . time() . rand(100, 999);
//$pathInS3 = 'https://s3.ap-south-1.amazonaws.com/' . $bucketName . '/' . $target_file;
// Add it to S3
try {
if (!file_exists('/tmp/tmpfile')) {
echo 3;
mkdir('/tmp/tmpfile');
}
$tempFilePath = '/tmp/tmpfile/' . basename($_FILES["ftp"]['name']);
$tempFile = fopen($tempFilePath, "w") or die("Error: Unable to open file.");
$fileContents = file_get_contents($_FILES["ftp"]['tmp_name']);
$tempFile = file_put_contents($tempFilePath, $fileContents);
$s3->putObject(array(
'Bucket' => $bucketName,
'Key' => $target_file,
'SourceFile' => $tempFilePath,
'StorageClass' => 'REDUCED_REDUNDANCY',
'ACL' => 'public-read'
));
$valPOutput = htmlspecialchars($target_file);
header('HTTP/1.1 303 See Other');
header('Location: http://example.com/result.php' . "?p=" . $valPOutput);
}
catch (S3Exception $e) {
die('Error:' . $e->getMessage());
}
catch (Exception $e) {
die('Error:' . $e->getMessage());
}
} else {
echo "image too big";
}
} elseif ($mimeType == "application/zip" || $mimeType == "application/x-rar-compressed" || $mimeType == "application/x-7z-compressed" || $mimeType == "application/x-bzip2") {
if ($fileSize <= 5000 * 1024 * 1024) { //max arch size
$target_dir = "f/";
//$strng = preg_replace("/[\s-]|\#/", "_", basename($_FILES["ftp"]["name"])); //Prima era solo "/[\s-]/"
$target_file = $target_dir . time() . rand(100, 999);
// $pathInS3 = 'https://s3.ap-south-1.amazonaws.com/' . $bucketName . '/' . $target_file;
// Add it to S3
try {
if (!file_exists('/tmp/tmpfile')) {
echo 3;
mkdir('/tmp/tmpfile');
}
$tempFilePath = '/tmp/tmpfile/' . basename($_FILES["ftp"]['name']);
$tempFile = fopen($tempFilePath, "w") or die("Error: Unable to open file.");
$fileContents = file_get_contents($_FILES["ftp"]['tmp_name']);
$tempFile = file_put_contents($tempFilePath, $fileContents);
$s3->putObject(array(
'Bucket' => $bucketName,
'Key' => $target_file,
'SourceFile' => $tempFilePath,
'StorageClass' => 'REDUCED_REDUNDANCY',
'ACL' => 'public-read'
));
$valPOutput = htmlspecialchars($target_file);
header('HTTP/1.1 303 See Other');
header('Location: http://example.com/result.php' . "?p=" . $valPOutput);
}
catch (S3Exception $e) {
die('Error:' . $e->getMessage());
}
catch (Exception $e) {
die('Error:' . $e->getMessage());
}
}else {
echo "arch too big";
}
}
}
?>
I've tried to do so adding event listeners to prevent submitting request, but when I upload a file, the website URL changes from https://example.com to https://example.com/awsUpload.php and the Progress Bar does not move and the Upload keeps going.
I'd like to receive some suggestions on how I can move or think to achieve that (the code I posted right now does not include any Progress bar test since I deleted the progress bar code cause it did not work).
EDIT DOWN HERE
Modified the form and added this new Script.
Right now the Load bar does work and the file gets uploaded, unfortunately I do not know why after the form gets submitted I do not get redirected to https://example.com/?p=****
<form id="contact-form" action="awsUpload.php" method="post" name="frmImage" enctype="multipart/form-data">
<input class="file-input" type="file" style="width:100%;"autocomplete="off" name="ftp" accept="image/*, .zip, .rar, .bzip" onchange="uploadFile(this.form)" class="file-up" id="fileFTP">
<progress id="upload-progress" value="0" max="100"></progress>
</form>
<script>
function uploadFile(form) {
var fileInput = form.querySelector('input[type="file"]');
var file = fileInput.files[0];
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', this.form, true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
var progressBar = form.querySelector('progress');
progressBar.value = percentComplete;
}
};
xhr.onload = function() {
if (xhr.status == 200) {
// File uploaded successfully
alert('success')
} else {
// An error occurred during the upload
}
};
xhr.send(formData);
}
</script>
Extra: I tried to ad in the action of if (xhr.status == 200) to redirect to a certain webpage with window.location but I'm missing the $valPOutput from the awsUpload.php and do not know how to get it.

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'));

php to javaScript

Please help me figure out the javaScript/jQuery equivalent of this php code.
<?php
$from = 'USD';
$to = 'INR';
$url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X';
$handle = #fopen($url, 'r');
if ($handle) {
$result = fgets($handle, 4096);
fclose($handle);
}
$allData = explode(',',$result);
$dollarValue = $allData[1];
echo 'Value of $1 in Indian Rupees is Rs. '.$dollarValue;
Try this...
You can use jquery ajax to pass values to php page and get output from ajax success.
$.ajax({
type: "POST",
url: "ajax.php",
data: {from:from,to:to},
success: function(data){
alert(data);
//you can get output form ajax.php, what you expected.
}
});
ajax.php
<?php
$from = $_POST['from'];
$to = $_POST['to'];
$url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X';
$handle = #fopen($url, 'r');
if ($handle) {
$result = fgets($handle, 4096);
fclose($handle);
}
$allData = explode(',',$result);
$dollarValue = $allData[1];
echo 'Value of $1 in Indian Rupees is Rs. '.$dollarValue;
Ref:http://api.jquery.com/jquery.ajax/
The equivalent of fopen in this context would be like doing an jQuery Ajax GET request, however since finance.yahoo.com is on a different domain and their server doesn't allow cross domain requests, the GET request would error. To get around this, you'd need to have the PHP script on the same domain and do a request to that.
Save Script on Server
parse.php
<?php
$response =array('result'=>'failed','message'=>'missing params');
if(isset($_GET['from']) && isset($_GET['to'])){
$from = $_GET['from'];
$to = $_GET['to'];
$url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from .'&X='. $to;
$handle = #fopen($url, 'r');
if ($handle) {
$result = fgets($handle, 4096);
fclose($handle);
}
$allData = explode(',',$result);
$dollarValue = $allData[1];
$response['result']=$dollarValue;
$response['message']="value sent";
}
echo json_encode($response);
?>
JavaScript method
function getData(from,to){
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr1 = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr1 = new ActiveXObject("Microsoft.XMLHTTP");
}
//path to your script
xhr1.open("GET", "http://localhost/practice/parse.php?from="+from+"&to="+to, true);
xhr1.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr1.send();
xhr1.onreadystatechange = display_data;
function display_data() {
if (xhr1.readyState == 4) {
console.log(xhr1.responseText);
//do what you want to do here
}
}
}

Providing php generated xml file to javascript parser

I am developing a smart tv app that plays live streams. App itself works fine, when i provide a valid xml playlist to it.
But when i use php to generate xml file (wich also generates fine), it doesnt work.
I get an error:
TypeError: 'null' is not an object (evaluating 'this.XHRObj.responseXML.documentElement')
Here is my php file that generates videoList.xml, it works 100%.
In short words, this script checks if MAC address in database, and if it is, then it writes videoList.xml with walid live streaming links.
SamsungAPI.php
<?php
$MAC = $_GET['MAC'];
require_once('../config.php');
//Remove brackets form array
$_INFO = preg_replace('/[{}]/', '', $_INFO);
$mysqli = new mysqli($_INFO['host'], $_INFO['db_user'], $_INFO['db_pass'], $_INFO['db_name']);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql="SELECT * FROM users WHERE admin_notes = '$MAC' ";
$rs=$mysqli->query($sql);
$rows=mysqli_num_rows($rs);
if ($rows == 1) {
//MAC FOUND
$row = mysqli_fetch_array($rs);
$username = $row['username'];
$password = $row['password'];
$file = "videoList.xml";
$txt_file = file_get_contents('http://' . $_SERVER['HTTP_HOST'] . '/get.php?type=starlivev3&username=' . $username . '&password=' . $password . '&output=hls');
$rows = explode("\n", $txt_file);
if(empty($rows[count($rows)-1])) {
unset($rows[count($rows)-1]);
$rows=array_map('trim',$rows);
}
$handle = fopen($file, "w+") or die('Could not open file');
fwrite($handle, "<?xml version=\"1.0\"?>"."\n");
fwrite($handle, "<rss version=\"2.0\">"."\n");
fwrite($handle, "<channel>"."\n");
foreach($rows as $row => $data)
{
//get row data
$row_data = explode(',', $data);
//replace _ with spaces
$row_data[0] = str_replace('_', ' ', $row_data[0]);
//generate playlist content
fwrite($handle, "<item>"."\n");
fwrite($handle, "<title>{$row_data[0]}</title>"."\n");
fwrite($handle, "<link>{$row_data[1]}</link>"."\n");
fwrite($handle, "<description> Reserved for EPG </description>"."\n");
fwrite($handle, "</item>"."\n");
}
fwrite($handle, "</channel>"."\n");
fwrite($handle, "</rss>");
fclose($handle);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
//MAC NOT FOUND
echo "MAC NOT FOUND";
}
mysqli_close($mysqli); // Closing Connection
?>
Then in samsung smart tv videoplayer app, i have xml parser like this:
Server.js
var Server =
{
/* Callback function to be set by client */
dataReceivedCallback : null,
XHRObj : null,
url : "http://myvalidhost.com/samsungAPI.php?MAC=02000027000b"
}
Server.init = function()
{
var success = true;
if (this.XHRObj)
{
this.XHRObj.destroy(); // Save memory
this.XHRObj = null;
}
return success;
}
Server.fetchVideoList = function()
{
if (this.XHRObj == null)
{
this.XHRObj = new XMLHttpRequest();
}
if (this.XHRObj)
{
this.XHRObj.onreadystatechange = function()
{
if (Server.XHRObj.readyState == 4)
{
Server.createVideoList();
}
}
this.XHRObj.open("GET", this.url, true);
this.XHRObj.send(null);
}
else
{
alert("Failed to create XHR");
}
}
Server.createVideoList = function()
{
if (this.XHRObj.status != 200)
{
Display.status("XML Server Error " + this.XHRObj.status);
}
else
{
var xmlElement = this.XHRObj.responseXML.documentElement;
if (!xmlElement)
{
alert("Failed to get valid XML");
}
else
{
// Parse RSS
// Get all "item" elements
var items = xmlElement.getElementsByTagName("item");
var videoNames = [ ];
var videoURLs = [ ];
var videoDescriptions = [ ];
for (var index = 0; index < items.length; index++)
{
var titleElement = items[index].getElementsByTagName("title")[0];
var descriptionElement = items[index].getElementsByTagName("description")[0];
var linkElement = items[index].getElementsByTagName("link")[0];
if (titleElement && descriptionElement && linkElement)
{
videoNames[index] = titleElement.firstChild.data;
if(linkElement.firstChild.data.substring(0,4) !="http"){
alert("asdasdasd "+linkElement.firstChild.data.substring(0,4));
var rootPath = window.location.href.substring(0, location.href.lastIndexOf("/")+1);
var Abs_path = unescape(rootPath).split("file://")[1]+linkElement.firstChild.data;
videoURLs[index] = Abs_path;
}
else{
videoURLs[index] = linkElement.firstChild.data;
}
videoDescriptions[index] = descriptionElement.firstChild.data;
}
}
Data.setVideoNames(videoNames);
Data.setVideoURLs(videoURLs);
Data.setVideoDescriptions(videoDescriptions);
if (this.dataReceivedCallback)
{
this.dataReceivedCallback(); /* Notify all data is received and stored */
}
}
}
}
Does anyone have any idea why doesnt it accept my generated xml file?
Regards
M
I figured it out, in php headers content type was wrong.
Changed
header('Content-Type: application/octet-stream');
to
header('Content-Type: application/xml');
Now it works perfect!

How do I grab an image on a server and display on a html page?

I am trying to get a canvas that I have saved to pop up in my html window. Not sure how to grab it on the html page because the save generates a random name for the image.
The Save code:
function saveImage() {
cursor.visible = false; stage.update();
var canvasData = testCanvas.toDataURL("image/png");
window.open(("../popup.html"));
var xmlHttpReq = false;
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
cursor.visible = true; stage.update();
}
else if (window.ActiveXObject) {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
alert (nameOfFile);
ajax.open('POST', 'testSave.php', false);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.onreadystatechange = function() {
console.log(ajax.responseText);
}
ajax.send("imgData="+canvasData);
}
The PHP:
<?php
// requires php5
define('UPLOAD_DIR', 'images/');
$img = $_POST['img'];
$img = str_replace('data:images/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
The popup.html
<div><strong>Image to display below</strong></div>
<script>
window.onload = function() {
document.getElementById('imgData="+canvasData').src = localStorage.getItem('images/');
};
</script>
Your PHP is already returning the $file that was created on the server.
So, you could POST with jQuery and add a callback that receives that unique filename created on the server (or the error message if an error occurred).
// create a dataUrl from the canvas
var dataURL= canvas.toDataURL();
// post the dataUrl to php
$.ajax({
type: "POST",
url: "upload.php",
data: {image: dataURL}
}).done(function( respond ) {
// you will get back the temp file name
// or "Unable to save this image."
console.log(respond);
});

Categories

Resources