How to store or upload audio file in specific location? - javascript

I need to store recorded voices at one specific location. How to store or upload recorded file to location?
Here is my script for upload audio file & upload.php file
This is my reference link: https://blog.addpipe.com/using-recorder-js-to-capture-wav-audio-in-your-html5-web-site/
//upload link
var upload = document.createElement('a');
upload.href="#";
upload.innerHTML = "Upload";
upload.addEventListener("click", function(event){
var xhr=new XMLHttpRequest();
xhr.onload=function(e) {
if(this.readyState === 4) {
console.log("Server returned: ",e.target.responseText);
}
};
var fd=new FormData();
fd.append("audio_data",blob, filename);
xhr.open("POST","upload.php",true);
xhr.send(fd);
})
li.appendChild(document.createTextNode (" "))//add a space in between
li.appendChild(upload)//add the upload link to li
upload.php
<?php
print_r($_FILES); //this will print out the received name, temp name, type, size, etc.
$size = $_FILES['audio_data']['size'];
$input = $_FILES['audio_data']['tmp_name'];
$output = $_FILES['audio_data']['name'].".wav";
move_uploaded_file($input, $output)
?>

target_dir=>where don you want to store it
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["audio_data"]["name"]);
if (move_uploaded_file($_FILES["audio_data"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["audio_data"]["name"]). " has been
uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}

Related

File is corrupted after converting

I am using recorder.js library and want to send the recorded message to my gmail account using PHPMailer. I have done everything but the only problem that I am getting is that when I send the file as an attachment and download it from my mail, it is corrupted (or whatever) and my system says "The file is unplayable". Moreover, when I check my local uploads/ folder where I am writing all the files, they are unplayable too. I don't know what seems to be the problem and I am stuck on this since past two days. Thanks in advance.
My JS call to upload.php
function sendMessage() {
var xhr = new XMLHttpRequest();
xhr.onload = function (e) {
if (this.readyState === 4) {
console.log("Server returned: ", e.target.responseText);
}
};
var fd = new FormData();
fd.append("audio_data", blob, filename);
xhr.open("POST", "upload.php", true);
xhr.send(fd);
}
and my upload.php
<?php
require "php-mailer-master/PHPMailerAutoload.php";
define('UPLOAD_DIR', 'uploads/');
$a = $_FILES['audio_data']['name'];
$a = str_replace('data:audio/wav;base64,', '', $a);
$a = str_replace(' ', '+', $a);
$data = base64_decode($a);
$file = UPLOAD_DIR . uniqid() . '.wav';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
Please note that I have skipped the part of code which is actually sending mail because I believe that is irrelevant.

Uploading capture image and store it in a folder changing it's filename to be unique using the userID

I have this code from this reference https://github.com/jhuckaby/webcamjs/blob/master/DOCS.md?fbclid=IwAR0Q3W5mw8qWlJEdiabmyZJiw7wGJ5YDPRl2Ej0IKF3GCt_78HXeqAEjI6Y
it will display the webcam and take snapshots and make it to an image element using the data_uri but the problem is I want to get that file and store it with a declared filename into a folder here's the script I use
<script src="webcam.js"></script> <!--source code script from github for webcam config-->
<div id="my_camera" style="width:320px; height:240px;"></div>
<div id="my_result"></div>
<script type=text/javascript>
Webcam.attach( '#my_camera' );
function take_snapshot() {
Webcam.snap( function(data_uri) {
document.getElementById('my_result').innerHTML = '<img src="'+data_uri+'"/>';
} );
}
</script>
Take Snapshot
I have a button called register that functions like get all information being input and store it into the database like username first name etc together with the image taken by snapshot, here's my upload script in uploading images from a folder and I want to use it as getting the image data_uri and store it in a folder when I click the register button
<?php
session_start();
include_once'database.php';
$uid = $_SESSION['u_id'];
if (isset($_POST['submit'])){
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
//check if ang uploaded file allowed i upload//
if (in_array($fileActualExt, $allowed)){
if ($fileError == 0){
if ($fileSize < 1000000){
$fileNameNew = "profile".$uid.".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
$sql = "UPDATE profileimg SET status=0 WHERE userID ='$uid';";
$result = mysqli_query($conn, $sql);
header("location:../pages/userpage.php");
}
else {
echo "Your file is too big";
}
} else {
echo "There was an error uploading you file!";
}
} else {
echo "You cannot upload files of this type";
}
}
I'm going to use this function as stated in the documentation
Webcam.upload( data_uri, 'myscript.php', function(code, text) {
// Upload complete!
// 'code' will be the HTTP response code from the server, e.g. 200
// 'text' will be the raw response content
} );
} );
and have this in my php script
move_uploaded_file($_FILES['webcam']['tmp_name'], 'webcam.jpg');
any idea how should I turn this script into the one I use above in my upload.php? thanks in advance
You need to create image first by image src and then need to save that in a specific folder. You can follow below code:
file_put_contents("fileNameWithLocation.png",file_get_contents($imageSrc));
Here fileNameWithLocation.png will be $fileNameNew = "profile".$uid.".".$fileActualExt; $fileDestination = 'uploads/'.$fileNameNew; You need to make modification accordingly. And $imageSrc will be the image src which you can post via Ajax or form submission.
Hope it helps you.

Uploading base64 pdf

I am making a file manager. Now I ran into the problem while trying to upload pdf files. The code I have so far that uploads images is working fine.
When i convert the pdf to a base64 string and open it in an tab, it shows the correct file and is working.
When I upload the file it uploads correctly, however when i open the uploaded file it seems to be corrupted.
Piece of code for uploading files i have:
JavaScript:
if(files[0].type.match(/\/pdf$/)){
var reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = function () {
uploadFile(reader.result, 'pdf', 'pdf', files[0].name);
console.log(reader.result); //shows correct base64
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
function uploadFile(file, name, type, file_name) {
var file_name = file_name.split('.')[0];
var $row = renderFileUploadRow(file_name, name);
$('body').append($row);
var fd = new FormData();
fd.append('file_data', file);
fd.append('do', 'upload');
fd.append('type', type);
fd.append('name', name)
fd.append('file_name', file_name);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'control.php?');
xhr.onload = function(data) {
$row.remove();
};
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
$row.find('.progress').css('width', (e.loaded / e.total * 100 | 0) + '%');
}
};
xhr.send(fd);
}
PHP receiving the ajax call:
if ($_POST['do'] == 'upload') {
$type = $_POST['type'];
$img = $_POST['file_data'];
$img = str_replace('data:image/'.$type.';base64,', '', $img);
echo "$type";
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
if ($type == 'jpeg') {
$type = 'jpg';
}
define('UPLOAD_DIR', 'data/'.$_POST['name'].'/');
$upload = UPLOAD_DIR . $_POST['file_name'] . '.'.$type;
if (file_exists($upload)==1){
$nummer = '1';
while(file_exists(UPLOAD_DIR . $_POST['file_name'] .'('. $nummer . ').'.$type)) {
$nummer++;
}
$upload = UPLOAD_DIR . $_POST['file_name'] .'('. $nummer .').'.$type;
}
$success = file_put_contents($upload, $data);
exit;
}
I expected to upload correctly because when i made images first and tested it, the files were uploaded correct. Now it uploads but the file is corrupted.
What am i doing wrong here?

Upload file to server asynchronously via form and XMLHttpRequest

I need to upload a file by only using vanilla.js, no frameworks are allowed.
Form:
<form id="fileUploadForm" action="fileUpload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
</form>
I placed the button outside of the form, because it is at another position in the HTML.
<button id="btnUpload">Upload</button>
This is the upload Script. I am using FormData to get the form data, as described in this answer.
<script>
document.getElementById("btnUpload").addEventListener("click", function() {
fileUpload("fileUploadForm");
});
function fileUpload(pFormId)
{
debugger;
var form = document.getElementById(pFormId);
var formData = new FormData( form ); //returns no data!
var request = getHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
console.log("Response Received");
document.getElementById("debug").innerHTML = request.responseText;
}
};
request.open("POST", "fileUpload.php", true);
// request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.setRequestHeader("Content-type","multipart/form-data");
formData.append("action","test"); //Add additional POST param
request.send(formData);
}
function getHttpRequest()
{
let xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
</script>
I am using the PHP upload script from here.
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} 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.";
}
}
I attached the debugger to my javascript and found out that formData is empty and does not contain the file.
This is what I get from PHP:
Sorry, file already exists.
Sorry, only JPG, JPEG, PNG & GIF files are allowed.Sorry, your file was not uploaded.
Even though the file does NOT already exists AND the file format is jpg.
Update:
This is what I get in the developers console network tab:
Request Payload:
------WebKitFormBoundaryKjnjAyPoCQ7MU1x6
Content-Disposition: form-data; name="fileToUpload"; filename="Koala.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryKjnjAyPoCQ7MU1x6--
I appreciate any help!
Just drop the content-type header, that will be set automatically by browser when using FormData. That way content-type will also contain form boundary used to separate form data (the thing like ------WebKitFormBoundaryKjnjAyPoCQ7MU1x6-- that separated the payload data).
I'd modify the code slightly.
document.getElementById("btnUpload").addEventListener("click", function() {
fileUpload("fileUploadForm");
});
You're binding the event on click. I'd modify this and attach a submit event to the form.
The closure will get the event target as callback:
document.getElementById("fileUploadForm").addEventListener("submit", function(e) { // <- pay attention to parameter
e.preventDefault(); // Prevent the default action so we stay on the same page.
fileUpload(e); // pass the event to your function
});
Now, on to your fileUpload function.
function fileUpload(e)
{
debugger;
var formData = new FormData( e.target ); // pass the event target to FormData which serializes the data
var request = getHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
console.log("Response Received");
document.getElementById("debug").innerHTML = request.responseText;
}
};
request.open("POST", "fileUpload.php", true);
request.setRequestHeader("Content-type","multipart/form-data");
request.send(formData);
}
Disclaimer: I did not test this at all, so don't copy paste and expect it to work!

AJAX won't execute all of the php code

I want a progressbar to be shown while a video-file is being uploaded. I'm using JS and AJAX to track progress of the file-upload php, and send the file. The php file contains a ffmpeg command that grabs some frames from the video. Essentially the php file creates a random folder, and puts both the video and the frames in it. when the php is called by if(isset($_FILES['file'])) it works just fine. But when i try to use AJAX it only uploads the video, but ignores the ffmpeg command and mysql_query.
Javascript:
function uploadFile(){
var file = _("file1").files[0];
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.open("POST", "upload.php");
ajax.send(formdata);
Upload.php
$name = $_FILES['file1']['name'];
$type = explode(".",$name);
$type = end($type);
$tmp = $_FILES['file1']['tmp_name'];
$uploadOk = 1;
$exp = explode(".",$name);
$filename = rand().$exp[0];
$path = "videos/" . $filename . "/" . $name;
$ffmpeg = "/usr/local/bin/ffmpeg";
$size = "320x180";
if($type != 'mp4' && $type != 'MP4'){
$message = "Only mp4 format is supported!";
$uploadOk = 0;
}else{
mkdir("videos/".$filename);
// ffmpeg function
for($num = 1; $num <= 15; $num++){
$interval = $num * 3;
shell_exec("$ffmpeg -i $tmp -an -ss $interval -s $size /videos/$filename/thumb$num.png");}
move_uploaded_file($tmp, $path);
mysql_query("INSERT INTO table (name, url) VALUES('$name', '$path')");
Why dosen't AJAX execute the complete php?

Categories