What do I need to add to my code here to add the ability to upload a video?
<div id="title">Upload Videos</div>
<div class="vidUpload">
<form id="vidUpload" enctype="multipart/form-data">
<input name="vidName" type="text" required="required" id="vidName" placeholder="Enter Video Name Here" title="Video Name">
<br>
<textarea name="videoDescription" id="videoDescription" required class="videoDescription" placeholder="Enter Video Description Here" title="Enter Video Description Here"></textarea>
<select name="select" required class="choosevidCat" id="choosevidCat">
<option value="">Choose the Catagory for your Video Here</option>
<?php
$sql = ("SELECT albumId, albumName, albumSelect FROM albums");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($mysqli, $sql);
while($row = mysqli_fetch_array($result)) {
$albumid = ($row['albumId']);
$album_name = ($row['albumName']);
$album_name1 = ($row['albumSelect']);
echo "<option value=".$album_name1. ">$album_name</option>";
}
?>
<option id="createCat" value="createCatagory">Create New Catagory Here</option>
</select>
<input type="file" name="video" id="video">
<input type="button" name="videoToUpload" id="videoToUpload" value="Upload">
</form>
<div id="loader"></div>
<div id="viduploadResult"></div>
jquery
<script type="text/javascript">
$(document).ready(function() {
$("#videoToUpload").click(function() {
var vidName = $("#vidName").val();
var videoDescription = $("#videoDescription").val();
var albumName1 = $("#choosevidCat").val();
var vidFile =$("#video").val();
// Put an animated GIF image insight of content
$("#loader").empty().html('<img src="/images/loader.gif" class="vidloader1"/>');
$.post("includes/vid_upload.inc.php",{vidName: vidName, videoDescription: videoDescription, albumName1: albumName1, vidFile: vidFile}, function(json)
{
if(json.result === "success") {
$("#viduploadResult").html( "The Video "+vidName+" has been Uploaded!");
// // First remove all the existing options
// $('#choosevidCat').empty();
//
// // Load the content:
// $('#choosevidCat').load(location.href + "#choosevidCat > *");
}else{
$("#viduploadResult").html(json.message);
}
});
});
})
</script>
I have spent hours looking at API's like blueimp etc, I just want to upload a video file and put it on my server from the form I have here.
Any help would be greatly appreciated
You are just passing the value of input type file. You should pass the file stream to your server script. Here is a sample code for uploading files using jquery.
Note: I am writing only jquery code to submit file. You must have to write server side code (PHP script) to upload the requested file.
Following code will help you to upload files. Customize it according to your scenario
if($("#video")[0].files.length)
{
this.total_files = $("#video")[0].files.length;
this.start_process = 0;
$.each($("#video")[0].files, function(i,o){
var files = new FormData();
files.append(1, o);
});
$.ajax({
url:"http://example.com",
method:"POST",
contentType:false,
processData: false,
data:files,
async:true,
xhr: function()
{
if(window.XMLHttpRequest)
{ var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with upload progress
}
}, false);
}
},
success:function(data){
alert("file uploaded..");
}
});
}
After further research I found this script and video tutorial which provided a resolution, so thought I would add it to my own question
Web Tutorial
https://www.developphp.com/video/JavaScript/File-Upload-Progress-Bar-Meter-Tutorial-Ajax-PHP
Video Tutorial
http://www.youtube.com/watch?v=EraNFJiY0Eg
Related
I am working on image upload in Php. I am trying to upload only jpeg images. Here is my code
$pkg_img = $_FILES['pkg_img']['name'];
$package_img = $ran.$pkg_img;
move_uploaded_file($_FILES['pkg_img']['tmp_name'],"../images/holiday-packages/" . $package_img);
$orgfile = "../images/holiday-packages/" . $package_img;
list($width,$height) = getimagesize($orgfile);
$newfile = imagecreatefromjpeg($orgfile);
$newwidth = $width*0.25;
$newheight = $height*0.25;
$thumb = "../images/holiday-packages/$ran1" . $package_img;
$new = $ran1.$package_img;
$truecolor = imagecreatetruecolor(640,320);
imagecopyresampled($truecolor,$newfile,0,0,0,0,640,320,$width,$height);
imagejpeg($truecolor,$thumb,100);
unlink($orgfile);
$sql = "update holidays set pkg_img = '$new' where id = '$id'";
When i upload png or gif images i am getting these errors
Warning: imagecreatefromjpeg(): gd-jpeg: JPEG library reports unrecoverable error: in C:\xampp\htdocs\justtravelservices\agent\upload-image.php on line 30
Warning: imagecreatefromjpeg(): '../images/holiday-packages/46logo-NEW.png' is not a valid JPEG file in C:\xampp\htdocs\justtravelservices\agent\upload-image.php on line 30
Warning: imagecopyresampled() expects parameter 2 to be resource, boolean given in C:\xampp\htdocs\justtravelservices\agent\upload-image.php on line 36
What i need is when user select Png, Gif or any other format before upload to the server instead of jpeg, i want to show a warning message like "Please select only jpeg image." Please help me.
If I assume you've this kind of HTML form to upload only JPG/JPEG files then you can try like this way on the front end to restrict only JPG/JPEG file uploading using simple javascript,
var handleUpload = function(event) {
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('image_id');
// you can change this line if you want ONLY JPEG support
if (!fileInput.files[0].name.match(/.(jpg|jpeg)$/i)){
console.log(fileInput.files[0].name);
alert('Not a JPG/JPEG image format');
}else{
alert('Image format is fine and it is either JPEG/JPG');
}
}
window.addEventListener('load', function(event) {
var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});
<form action="" method="post" enctype="multipart/form-data">
<input name="image" id="image_id" type="file" size="25" value="Select Image" />
<input type="submit" id="submit" value="Upload"/>
</form>
</div>
Good evening guys, I got a problem in the back-end of my system when I submit my form. It said Unidentified index: file1 . I can't fine the error here in my code.
I'm not a newbie in javascript and seeking for help from you guys. Advance thank you.
So here is my HTML form
<form id="submit_form" action="<?php echo base_url()?>Homepage/add_blog" enctype="multipart/form-data" method="POST" >
<input type="text" class="form-control" id="title" name="title" autocomplete="off">
<input type="text" class="form-control" id="lead" name="lead" autocomplete="off">
<input type="text" id="tags" name="tags" data-role="tagsinput" placeholder="Add tags" class="form-control" >
<input type="file" id="file1" name="file1" >
<textarea id="content" name="content" rows="10" cols="80">
Put the content here!!!
</textarea>
</form>
Here is my script
<script>
function _(el)
{
return document.getElementById(el);
}
$(document).ready(function()
{
$('#submit').click(function(e)
{
e.preventDefault();
var file = _("file1").files[0];
var title = $('#title').val();
var lead = $('#lead').val();
var tags = $('#tags').val();
var content = $('#content').val();
if(title == '' || lead == '' || tags == '' || content =='')
{
$('#response').html('<br><div class="panel panel-danger"><div class="panel-body"><center><span class="text-danger">All fields are required</span></center></div></div>');
$('#response2').html('<div class="panel panel-danger"><div class="panel-body"><center><span class="text-danger">All fields are required</span></center></div></div><br>');
}
else
{
$.ajax({
url:"<?php echo base_url()?>Homepage/add_blog",
method:"POST",
data:$('#submit_form').serialize(),
beforeSend:function()
{
$('response').html('<span class="text-danger">Loading...</span>');
$('#submit').prop("disabled", true);
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("error",abortHandler,false);
ajax.open("POST","<?php echo base_url()?>Homepage/add_blog");
ajax.send(formdata);
},
success:function(data)
{
$('form').trigger("reset");
$('#tags').tagsinput('removeAll');
$('#tags').tagsinput('destroy');
CKEDITOR.instances.content.setData('');
$('#response').fadeIn().html(data);
}
});
}
});
$('#title,#lead,#tags,#content').focus(function(){
$('#submit').prop("disabled", false);
});
});
function progressHandler(event)
{
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded;
var percent = (event.loaded/event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded.. please wait";
}
function completeHandler(event)
{
_("progressBar").value = 0;
}
function errorHandler(event)
{
_("status").innerHTML = "Upload Failed.";
}
function abortHandler(event)
{
_("status").innerHTML = "Upload Aborted.";
}
</script>
And the problem relies here in the back-end Homepage/add_blog:
$filename = $_FILES["file1"]["name"];
echo $filename;
If you any more details needed to solve this. Just comment. Need to fix this as soon as possible. Thank you again.
Undefined index notice that the array $_FILES does not contain the "file1" key set. Probably the way you are trying to send the file via ajax is not working properly.
I'd recommend you try to use FormData. I believe the link below is a good reference to solve your problem.
How to use FormData for ajax file upload
I have a php file which takes a zip file and unpacks it then places it at the desired path on my server.
It works great with a typical form that calls on the php file in the action. I am trying to make this work with AJAX but I have tried every piece of code I can find without any luck.
Is there something here I am missing? Surely this can be done?
Form for uploading the zip file,
<div id="response"></div>
<form enctype="multipart/form-data" method="post" action="">
<label>Choose a zip file to upload: <input type="file" name="zip_file" id="zip_file" /></label>
<br />
<input type="submit" name="submit" value="Upload" onClick="uploadZip()" />
</form>
Current JS - I get no errors, the page actually reloads with my current script..
<script>
function uploadZip() {
formdata = new FormData();
if (formdata) {
$('.main-content').html('<img src="LoaderIcon.gif" />');
$.ajax({
url: "assets/upload-plugin.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res){
document.getElementById("response").innerHTML = res;
}
});
}
}
</script>
php script which handles uploading the zip and unzipping it before placing it on the server.
function rmdir_recursive($dir) {
foreach(scandir($dir) as $file) {
if ('.' === $file || '..' === $file) continue;
if (is_dir("$dir/$file")) rmdir_recursive("$dir/$file");
else unlink("$dir/$file");
}
rmdir($dir);
}
if($_FILES["zip_file"]["name"]) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "The file you are trying to upload is not a .zip file. Please try again.";
}
/* PHP current path */
$path = '../plugins/'; // absolute path to the directory where zipper.php is in
$filenoext = basename ($filename, '.zip'); // absolute path to the directory where zipper.php is in (lowercase)
$filenoext = basename ($filenoext, '.ZIP'); // absolute path to the directory where zipper.php is in (when uppercase)
$targetdir = $path . $filenoext; // target directory
$targetzip = $path . $filename; // target zip file
/* create directory if not exists', otherwise overwrite */
/* target directory is same as filename without extension */
if (is_dir($targetdir)) rmdir_recursive ( $targetdir);
mkdir($targetdir, 0777);
/* here it is really happening */
if(move_uploaded_file($source, $targetzip)) {
$zip = new ZipArchive();
$x = $zip->open($targetzip); // open the zip file to extract
if ($x === true) {
$zip->extractTo($targetdir); // place in the directory with same name
$zip->close();
unlink($targetzip);
}
$message = "Your .zip file was uploaded and unpacked.";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
This php function works great as long as I do this with the form action. So I am sure my problem exist in the AJAX function.
Thanks for any help you can provide.
formdata = new FormData();
You've created a FormData object but you never put any data into it.
The easiest approach is to specify the form:
formdata = new FormData(document.forms[0]);
You also need to stop the submit button from actually submitting the form so that the JS can do something.
A cleaner approach would be to:
Stop using intrinsic event attributes
Use the submit handler for the form
Get the form from the event
<input type="submit" name="submit" value="Upload" onClick="uploadZip()" />
Becomes:
<input type="submit" name="submit" value="Upload">
function uploadZip() {
formdata = new FormData();
becomes:
function uploadZip(event) {
var formdata = new FormData(this);
// Rest of function
event.preventDefault();
}
and you add:
jQuery("form").on("submit", uploadZip);
I'm new here and I'm sorry if i have posted this in the wrong place or anything.
What i want to implement is a text which displays percentage from 1%-100% which shows how much a file has been uploaded.
Right now, It shows just "Loading.." Instead of uploading..
I'm using PHP and JS in the website. Here is the script for the "Loading" button.
echo "<form id=\"uploads\" action=\"\" method=\"post\" enctype=\"multipart/form-data\"><input type=\"hidden\" value=\"myForm\" name=\"$upload_name\">
<center><input type=\"file\" value=\"Upload\" name=\"upload_file[]\" class=\"file\" multiple class=\"button2\"/> <br><br><input type=\"button\" id=\"upload\" class=\"button2\" value=\"Upload\" onclick=\"document.getElementById('upload').disabled = 'disabled'; document.getElementById('upload').value = 'Loading...'; document.getElementById('uploads').submit();\"><br><br></center>
</form></center>
";
How can i implement this? Please direct me to the path where i can implement this feature.
So a "without library" solution. Provide the URL of your server upload handler, select your file and click on upload. You should see the progression as a percentage.
document.querySelector("#upload").addEventListener("click",function(){
var oReq = new XMLHttpRequest();
oReq.addEventListener("progress", updateProgress, false);
oReq.addEventListener("load", transferComplete, false);
oReq.addEventListener("error", transferFailed, false);
oReq.addEventListener("abort", transferCanceled, false);
var upload_to_URL= document.querySelector("#upload_to").value;
oReq.open('POST', upload_to_URL , true);
var formData = new FormData();
formData.append("upload", file.files[0]);
oReq.send(formData);
});
// progress on transfers from the server to the client (downloads)
function updateProgress (oEvent) {
if (oEvent.lengthComputable) {
var percentComplete = oEvent.loaded / oEvent.total;
// ...
document.querySelector("#upload-progress").innerHTML= (percentComplete * 100 ) + "%"
} else {
// Unable to compute progress information since the total size is unknown
}
}
function transferComplete(evt) {
document.querySelector("#upload-progress").innerHTML= " <span style='color:green'>100%</span>";
}
function transferFailed(evt) {
alert("An error occurred while transferring the file.");
}
function transferCanceled(evt) {
alert("The transfer has been canceled by the user.");
}
<form id="upload-form">
<input type="text" id="upload_to" placeholder="Upload handler URL"/><br />
<input type="file" id="file"/>
<input type="submit" value="upload" id="upload" />
</form>
<div id="upload-progress"></div>
sorry if I am being redundant but I've tried every single example I found here and on google :D
What I am trying to do is on the upload of image, what was typed on inputbox will be send along to the uplodify.php where my insert is. My problem is, name of picture has being saved to the mysql but what was typed on the textfield dont.
Would you guys let me know what is going on?
This is the part of my code
'multi' : true,
'auto' : false,
'onUploadStart' : function(file) {
$("#file_upload").uploadify('settings', 'formData', {'galeria': $('#galeria').val()});
},
<form id="form1" name="form1" action="">
<p>
<input type="file" id="file_upload" name="file_upload" />
<br>
<br>
Galeria<br>
<label>
<input type="text" name="galeria" id="galeria">
uplodify.php
$galeria = $_POST['galeria'];
$regiao = $_POST['regiao'];
if (!empty($_FILES)) {
$img = $_FILES['Filedata']['name'];
$ext = substr($img, -4);
$img = md5($img).date("dmYHis").$ext;
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//','/',$targetPath) . $img;
$adicionar = mysql_query ("INSERT INTO imagens (foto, galeria, regiao) VALUES('$img','$galeria','$regiao')");
// $fileTypes = str_replace('*.','',$_REQUEST['fileext']);
// $fileTypes = str_replace(';','|',$fileTypes);
// $typesArray = split('\|',$fileTypes);
// $fileParts = pathinfo($_FILES['Filedata']['name']);
// if (in_array($fileParts['extension'],$typesArray)) {
// Uncomment the following line if you want to make the directory if it doesn't exist
// mkdir(str_replace('//','/',$targetPath), 0755, true);
move_uploaded_file($tempFile,$targetFile);
echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile);
// } else {
// echo 'Invalid file type.';
// }
}
Try changing your onUploadStart method to extend the uploadify formData property like this:
onUploadStart: function ( file ) {
var $fileUpload = $('#file_upload')
, formData = $fileUpload.uploadify('settings', 'formData')
, newFormData = $.extend({}, formData, { galeria: $('#galeria').val() });
$fileUpload.uploadify('settings', 'formData', newFormData);
}
I finally managed to made it work
This is the code I used
$('#file_upload').attr('file_upload', response).show();
$.post("insert2.php",{name: fileObj.name, galeria: $("#galeria").val(), regiao: $("#regiao").val()}, function(info) {
alert(info); // alert UPLOADED FILE NAME
});
}
});
Now I have a different problem lol it always show right...
Since the code to save the file on dabase is on insert2.php and the code to rename the picture inside the uploadify.php. How can I save the new name on the database instead the name of file I uploaded?
Another question.... is that a way to generate a thumbnail based on those pictures on database?