Audio File Not Getting Uploaded with ajax - javascript

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;
}
?>

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.

Can't send XMLHttpRequest

I am trying to delete data with vanilla javascript ajax. After sending POST request with an id value to php file. Every time it prints "error" in the console.
HTML
<div class="deleteButton" onclick="showAllert(this)" id="1">
<i class="fa-solid fa-trash-can fa-2x" style="color:#A81E22" title="delete"></i>
</div>
JAVASCRIPT
<script>
function showAllert(a) {
// sent delete request
var dataId = a.getAttribute("id");
var dataId = parseInt(dataId);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'includes/vehicles/del-veh.php', true);
// xhr.responseType = 'json';
xhr.onload = () => {
if(xhr.status === 200) {
console.log(xhr.response);
location.reload();
}else {
console.log("There was a problem");
}
}
var data = JSON.stringify({id: dataId});
xhr.send(data);
}
</script>
PHP
<?php
//Connection statement
require_once('../../Connections/ukcd.php');
$data = json_decode(file_get_contents('php://input'), true);
if(!empty($data["id"])) {
// Required variables
$vehid = $data['id'];
echo "success";
}else {
echo "error";
}
//AUTOEXECUTE METHOD
$delveh = $ukcd->prepare('DELETE FROM a_ukcd_client_vehicles WHERE clientveh_id = ?');
$result = $ukcd->execute($delveh, $vehid);
Send POST data in urlencoded format:
<script>
function showAllert(a) {
// sent delete request
var dataId = a.getAttribute("id");
var dataId = parseInt(dataId);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'includes/vehicles/del-veh.php', true);
// xhr.responseType = 'json';
xhr.onload = () => {
if(xhr.status === 200) {
console.log(xhr.response);
location.reload();
}else {
console.log("There was a problem");
}
}
// var data = JSON.stringify({id: dataId});
xhr.send(`id=${dataId}`);
}
</script>
And in your PHP script:
<?php
//Connection statement
require_once('../../Connections/ukcd.php');
$id= $_POST['id'];
if(!empty($id)) {
// Required variables
$vehid = $id;
echo "success";
}else {
echo "error";
}
//AUTOEXECUTE METHOD
$delveh = $ukcd->prepare('DELETE FROM a_ukcd_client_vehicles WHERE clientveh_id = ?');
$result = $ukcd->execute($delveh, $vehid);

Call data back from AJAX

I have a script which saves canvas PNGs to a directory and I need the URL to save on the server.
When I submit, the image saves but the server remains empty. I am trying to return error messages but I am receiving nothing.
JAVASCRIPT:
function doodleSave() {
var drawing = document.getElementById("doodle-canvas");
var drawingString = drawing.toDataURL("image/png");
var postData = "canvasData="+drawingString;
var ajax = new XMLHttpRequest();
ajax.open("POST", 'http://www.website.com/php/doodleSave.php', true);
ajax.onreadystatechange= function() {
if (ajax.readyState === 4) //If it ran smoothly
{$("#doodle-submit-button").html("...");}
};
ajax.send(postData);
ajax.success(function(data) {
{$("#doodle-submit-button").html(""+data+"");}
});
}
PHP:
<?php
session_start();
if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
$rawImage = $GLOBALS['HTTP_RAW_POST_DATA'];
$removeHeaders = substr($rawImage, strpos($rawImage, ",")+1);
$url = md5(uniqid(rand(), true));
$decode = base64_decode($removeHeaders);
$fopen = fopen('../images/external/doodles/'.$url.'.png', 'wb');
fwrite($fopen, $decode);
fclose($fopen);
//ADD POST TO DATABASE WITH USER'S ID
/* AUTOMATED VARIABLES */
$unique_user_id = $_SESSION['unique_user_id'];
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = 'images/external/doodles/'.$url;
try
{
$stmt = $pdo->prepare("INSERT INTO `(table name)` (unique_user_id, unique_post_id, nature, image_url, timestamp) VALUES(:unique_user_id, :unique_post_id, :nature, :image_url, :timestamp)");
$stmt->bindParam(":unique_user_id",$profile_unique_user_id);
$stmt->bindParam(":unique_post_id",$unique_post_id);
$stmt->bindParam(":nature",$nature);
$stmt->bindParam(":image_url",$imageUrl);
$stmt->bindParam(":timestamp",$timestamp);
if($stmt->execute())
{
echo "uploaded";
}
else
{
echo "Could not upload";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>

How to receive & process data sent to php with XMLHttpRequest?

I'm working on upload form for mp3 files and I hit a wall :/. Can you help please?
Here is my HTML:
<form id="file-form" method="POST">
<input class="profileMenu" id="mp3file" name="mp3file" type="file" multiple/>
</form>
<div onclick="test()" class="col-md-1 profileMenu" id="uploadButton">Upload</div>
Here is my JavaScript:
function test() {
var form = document.getElementById('file-form');
var fileSelect = document.getElementById('mp3file');
var uploadButton = document.getElementById('uploadButton');
uploadButton.innerHTML = 'Uploading...';
var files = fileSelect.files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
var file = files[i];
formData.append('mp3file', file, file.name);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'php/commercial/upload.php', true);
xhr.onload = function () {
if (xhr.status === 200) {
uploadButton.innerHTML = 'Upload';
}
else {
alert('An error occurred!');
}
};
xhr.send(formData);
}
}
And lastly my PHP:
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['filename']['name']);
if(move_uploaded_file($_FILES['filename']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['filename']['name']). " has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
I'm trying to upload mp3 files to my server and sort them in folders, form validation is going ok, request doesn't return any errors and it seems my php code is not doing what it should be, I know i can do it with submit button without using JavaScript but i need to do it this way. So if any of you have any idea i would be very thankful.

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