Combine $_FILES and $_POST into one AJAX call with Javascript only - javascript

I am having difficulty sending an ajax call that contains both a file and a string. I have no difficulty making either post or file, but not both together. I need this in pure Javascript, which i am more proficient than Jquery.
here is the code i am working with...
function uploadFile(){
var title = _('title').value;
var genere = _('genere').value;
var stars = _('stars').value;
var description = _('description').value;
var file = _("video").files[0];
//alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("video", file);
formdata.append("title", title);
formdata.append("genere", genere);
formdata.append("stars", stars);
formdata.append("description", description);
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", "video_php/video_upload.php");
ajax.send(formdata);
}
function progressHandler(event){
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";
}
This is the php.....
<?PHP
$fileName = '';
$fileTmpLoc = '';
$fileType = '';
$fileSize = '';
$title = '';
$genere = '';
$stars = '';
$description = '';
$retn= '';
if (!isset($_FILES["video"]["name"])) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}else{
$fileName = $_FILES["video"]["name"]; // The file name
$fileTmpLoc = $_FILES["video"]["tmp_name"]; // File in the PHP tmp folder
$fileType = explode('.',$fileName); // The type of file it is
$fileType = end($fileType); // The end type of file it is
$fileSize = $_FILES["video"]["size"]; // File size in bytes
$title = preg_replace('#[^a-z0-9, ]#i', '', $_POST['title']);
$genere = preg_replace('#[^a-z0-9, ]#i', '', $_POST['genere']);
$stars = preg_replace('#[^a-z0-9, ]#i', '', $_POST['stars']);
$description = preg_replace('#[^a-z0-9, ]#i', '', $_POST['description']);
}
echo $fileName.'<br/>';
echo $fileTmpLoc.'<br/>';
echo $fileType.'<br/>';
echo $fileSize.'<br/>';
echo $title.'<br/>';
echo $genere.'<br/>';
echo $description.'<br/>';
?>
I have been stuck on this for weeks. I have been through SO as well as many other sites with google. Every answer CLOSE to my desired result has been in Jquery. One solution i had was to make a 2-step form, uploading first one dataset, then the other, but i think both can be sent together for user usability. I have seen it done on several other websites.
NOTE*
Above code has been corrected. Added
formdata.append("video", file);
formdata.append("title", title);
formdata.append("genere", genere);
formdata.append("stars", stars);
formdata.append("description", description);
It is now fully functional, thanks to #Ohgodwhy
Origional Question is at Send $_POST and $_FILE data to php with JAVASCRIPT

Looks like you want the value of _('title') to be added to the formdata.
Given that you have this:
formdata.append("video", file);
All you need to do is this:
formdata.append('title', title);
The FormData object will handle the transmission of the file, and title will be available as $_POST['title'];

Related

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?

php: customizing file upload

Following a tutorial i get a basic php file upload form, i'm newbie of php, May i ask how to get five file upload forms to send five files at the same time, each one with its own progress bar, but with a single button to start uploading all, also how to rename to a specific name the output files and to get only a specified MIME type possible to be uploaded.
Im unable to use this code in amodular way, to economize the code, without copy and paste all things.
Thanks a lot
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("progress", 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>UPGRADE ADAPTIVE-SETS</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"]["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, "incoming/$fileName")){
echo "$fileName upload is complete";
} else {
echo "move_uploaded_file function failed";
}
?>
<?php
if(isset($_FILES['file']))
{
$error = $_FILES['file']['error'];
if($error != 0)
{
echo 'Upload error.';
}
else
{
$size = $_FILES['file']['size'];
if($size > (1024*1024*3))
{
echo 'file < 3MB ';
}
else
{
$tip = $_FILES['file']['type'];
$name = $_FILES['file']['name'];
$extension = explode('.', $name);
$extension = $extension[count($extension)-1];
if($extension == 'jpg' || $extension == 'png' || $extension == 'gif')
{
if(!file_exists('files'))
mkdir('files');
$file = $_FILES['file']['tmp_name'];
copy($file, 'files/' . $_FILES['file']['name']);
echo 'Uploaded ';
}
else
{
echo 'Just =>JPG,PNG.';
}
}
}
}?>
Hi, For example, the example in this code

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?

how to send input text value

My problem is I don't know how to send inputs text values with code below.
I find this code in some website but I don't know how to send inputs text values with it because it send just files.
<script>
/* Script written by Adam Khoury # DevelopPHP.com */
/* Video Tutorial: http://www.youtube.com/watch?v=EraNFJiY0Eg */
function _(el){
return document.getElementById(el);
}
function uploadFile(){
var file = _("file1").files[0];
var name = _("name").value;
// alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
formdata.append("name", 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", "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>
<input type="text" name="name" placeholder="title" id="name"/>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
And this php code :
<?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"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
$name = $_POST['name'];
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "$fileName")){
echo "$fileName upload is complete $name";
} else {
echo "move_uploaded_file function failed";
}
?>
Please help me by editing my code and thank you.
You Just need to change code
EDIT JS FROM
var formdata = new FormData();
formdata.append("file1", file);
formdata.append("name", file); // IMPORTANT : FROM THIS
EDIT JS TO
var formdata = new FormData();
formdata.append("file1", file);
formdata.append("name", name); // IMPORTANT : TO THIS
FRONT END CODE
<head>
<script>
/* Script written by Adam Khoury # DevelopPHP.com */
/* Video Tutorial: http://www.youtube.com/watch?v=EraNFJiY0Eg */
function _(el){
return document.getElementById(el);
}
function uploadFile(){
var file = _("file1").files[0];
var name = _("name").value;
// alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
/////////////////////////////////////////////////////////////////////
formdata.append("name", name); ////// formdata.append("name", 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", "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>
<input type="text" name="name" placeholder="title" id="name"/>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
PHP CODE
$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
$name = $_POST['name'];
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, $fileName)){
echo $fileName . 'upload is complete ' . $name;
} else {
echo "move_uploaded_file function failed";
}
Run a separate function in your completeHandler() that uploads the text data via ajax after your image has uploaded.

PHP move_uploaded_file uploads only one file

I'm testing uploads on 3 files on my desktop test.xlsx, test - Copy.xlsx, and test - Copy (2).xlsx. My PHP script is breaking at the line where my move_uploaded_files statement is. I get the error move_uploaded_file(uploads/test - Copy.xlsx): failed to open stream: No such file or directory. BUT test - Copy (2).xlsx is uploaded when I check my uploads folder. My PHP is as follows:
foreach($_FILES['file']['name'] as $key=>$value){
$fileName = $_FILES['file']['name'][$key];
$fileTmpLoc = $_FILES['file']['tmp_name'][$key];
$fileErrorMsg = $_FILES['file']['error'][$key];
$type = $_FILES['file']['type'][$key];
if(){
//validation
} else{ //if validated
if(move_uploaded_file($fileTmpLoc, 'uploads/'.$fileName)){
//do more stuff
} else{
echo "Upload failed.";
}
}
}
The //do more stuff actually runs once for test - Copy (2).xlsx (the only file uploaded successfully). My JS script is below but I doubt that's the part that's breaking since when I print_r($_FILES) in PHP, all files appear in the output.
var upload = function(event){
var file = document.getElementById('file').files;
var data = new FormData();
for (i=0; i<file.length; i++){
data.append('file[]', file[i]);
}
var request = new XMLHttpRequest();
request.addEventListener('load', completeHandler, false);
request.addEventListener('error', errorHandler, false);
request.addEventListener('abort', abortHandler, false);
request.open('POST', 'php/excel_upload_read.php');
request.send(data);
};
What am I doing wrong?
Looks like you are using the multi-dimensional array in the wrong order. Try this:
foreach($_FILES['file'] as $key=>$value){
$fileName = $_FILES['file'][$key]['name'];
$fileTmpLoc = $_FILES['file'][$key]['tmp_name'];
$fileErrorMsg = $_FILES['file'][$key]['error'];
$type = $_FILES['file'][$key]['type'];
...
}
The problem is the way $_FILES global is structured, it does not let you iterate easily.
You can use this function it s meant to reorganize the data structure
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
Then you can use foreach easily:
if(isset($_FILES['file']['tmp_name'], $_POST)) {
$files = reArrayFiles($_FILES['file']);
foreach ($files as $file) {
$temp = $file['tmp_name'];
$path = 'uploads/'.$file['name'];
if(move_uploaded_file($temp, $path)){
echo 'Upload succesful';
}else{
echo 'failed to upload';
}
}
}else{
echo 'file not uploaded';
}
This function reArrayFiles was posted by someone in the PHP documentation:
http://php.net/manual/en/features.file-upload.multiple.php

Categories