Multiple images uploading is not working multiple times in a page - php

I am trying to edited multiple images upload in more than once.
But is not working.Please update any suggestions or answer.
Below sample code:
<div id="upload_form" class="hide">
<form action="multi_files.php" target="hidden_iframe" enctype="multipart/form-data" method="post">
<input type="file" multiple name="upload_files[]" id="upload_files">
</form>
</div>
<div align="center" style="padding:10px">
<button onclick="Uploader.upload();" class="btn btn-primary btn-lg">Upload Files</button>
<div id="wait" class="hide"><img src="upload-indicator.gif" alt=""></div>
</div>
<div>
<iframe name="hidden_iframe" id="hidden_iframe" class="hide"></iframe>
</div>
<div id="uploaded_images" align="center">
</div>
Here I am add this code for another upload option with different form.
But is not working.Below the edited code:
<!--####### Below Edited as same on above #######-->
<div id="upload_form_cover" class="hide">
<form id="upload_form_cover" action="multi_files_cover.php" target="hidden_iframe" enctype="multipart/form-data" method="post">
<input type="hidden" name="image_type" value="cover_image" >
<input type="file" multiple name="upload_files_cover[]" id="upload_files_cover">
</form>
</div>
<div align="center" style="padding:10px">
<button onclick="Uploader_cover.upload();" class="btn btn-primary btn-lg">Upload Files TEST</button>
<div id="wait_cover" class="hide"><img src="upload-indicator.gif" alt=""></div>
</div>
JavaScript Code :
<script type="text/javascript">
var Uploader = (function () {
jQuery('#upload_files').on('change', function () {
jQuery("#wait").removeClass('hide');
jQuery('#upload_files').parent('form').submit();
});
var fnUpload = function () {
jQuery('#upload_files').trigger('click');
}
var fnDone = function (data) {
var data = JSON.parse(data);
if (typeof (data['error']) != "undefined") {
jQuery('#uploaded_images').html(data['error']);
jQuery('#upload_files').val("");
jQuery("#wait").addClass('hide');
return;
}
var divs = [];
for (i in data) {
divs.push("<div><img src='" + data[i] + "' style='height:100px' class='img-thumbnail'></div>");
}
jQuery('#uploaded_images').html(divs.join(""));
jQuery('#upload_files').val("");
jQuery("#wait").addClass('hide');
}
return {
upload: fnUpload,
done: fnDone
}
}());
<!--####### Belo Edited as same on above for form id: upload_form_cover #######-->
var Uploader_cover = (function () {
alert("Uploader_cover");
jQuery('#upload_files_cover').on('change', function () {
jQuery("#wait_cover").removeClass('hide');
jQuery('#upload_form_cover').submit();
});
var fnUpload = function () {
jQuery('#upload_files_cover').trigger('click');
}
var fnDone = function (data) {
var data = JSON.parse(data);
if (typeof (data['error']) != "undefined") {
jQuery('#uploaded_images_cover').html(data['error']);
jQuery('#upload_files_cover').val("");
jQuery("#wait_cover").addClass('hide');
return;
}
var divs = [];
for (i in data) {
divs.push("<div><img src='" + data[i] + "' style='height:100px' class='img-thumbnail'></div>");
}
jQuery('#uploaded_images_cover').html(divs.join(""));
jQuery('#upload_files_cover').val("");
jQuery("#wait_cover").addClass('hide');
}
return {
upload: fnUpload,
done: fnDone
}
}());
</script>
</body>

You are not submitting the right dom ie form in both functions. Put this.
jQuery('#upload_files').on('change', function () {
jQuery("#wait").removeClass('hide');
$(this).parent().submit();
});

First create a "arts" folder for putting image on it
index.html
<form id="upload" method="post" action="upload.php" enctype="multipart/form-data">
<input type="file" name="upl" multiple />
</form>
upload.php
<?php
$allowed = array('png', 'jpg', 'jpeg', 'gif', 'swf'); //The file you want to user put
if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){
$extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
if(move_uploaded_file($_FILES['upl']['tmp_name'], 'arts/'.$_FILES['upl']['name'])){
echo '{"status":"success"}';
exit;
}
}
echo '{"status":"error"}';
exit;
?>

Related

How to pass a video recorded by MediaRecorder through HTML form

I'm trying to passing, through HTML form, a MediaRecorder file but it doesn't work. The code is the following:
This is the code which record the audio
function hasGetUserMedia() {
return !!( navigator.mediaDevices && navigator.mediaDevices.getUserMedia );
}
function audioPlay(){
if ( hasGetUserMedia() ) {
audioRunner();
}else{
console.log('UserMedia not supported');
}
}
function audioRunner(){
var audio = document.getElementById('audio');
let audioButtons = {
start: document.getElementById('audio_recorder'),
stop: document.getElementById('audio_stop'),
}
let boxAudio = {
input: document.getElementById('input_audio')
}
let chunks = [];
let constraintObj = {
audio: true
}
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia(constraintObj).then(function(stream) {
let mediaRecorder = new MediaRecorder(stream);
//BUTTONS
audioButtons.start.addEventListener('click', (ev) => {
mediaRecorder.start();
startAnimation();
console.log(mediaRecorder.state);
});
audioButtons.stop.addEventListener('click', (ev) => {
mediaRecorder.stop();
stopAnimation();
console.log(mediaRecorder.state);
})
mediaRecorder.ondataavailable = function(ev){
chunks.push(ev.data);
}
mediaRecorder.onstop = (ev) => {
let blob = new Blob(chunks, { 'type' : 'audio/mpeg-3' });
let videoURL = window.URL.createObjectURL(blob);
audio.src = videoURL;
audio.style.display = 'block';
fr = new FormData();
fr.append('blob', videoURL);
boxAudio.input.value = fr;
console.log(fr);
chunks = [];
}
<form enctype="multipart/form-data" action="views/send_message_form.php" method="post">
<div class="card bg-light message_ctn" id="audio_message_ctn">
<div class="card-header">Header</div>
<div class="card-body">
<div id="microphone-icon">
<span data-color="red"><i class="fas fa-microphone-alt"></i></span>
</div>
<audio id="audio" controls></audio>
<input type="text" name="audio_message" id="input_audio">
<div id="audio_buttons" class="box_buttons">
<button type="button" id="audio_recorder" class="btn btn-outline-primary">Registra</button>
<button type="button" id="audio_stop" class="btn btn-outline-info">Stop</button>
<button type="submit" id="audio_send" class="btn btn-outline-success">Invia</button>
</div>
</div>
</div>
</form>
and this is the code PHP that receives the data by form
var_dump($_POST);
?>
<video src="<?=$_POST['audio_message'] ?>"></video>
When I submit the form the variable $_POST is empty, How can I pass the video to send_message_form.php and then save it into htdocs sub-folder?

how to submit a form after a file has been uploaded while including some data in the post[]

hi i have following html form and i am using it to upload a .xlx file.
<form action="dashboard.php" method="post" enctype="multipart/form-data">
<div class="file-upload">
<div class="col-md-12 m-b-15">
<div class="col-md-3">
Note No :
</div>
<div class="col-md-8">
<input class=" form-control m-b-15 " id="note_number_for_the_alert" name="note_number_for_the_alert" readonly="">
</div>
</div>
<div class="row">
<div class="col-md-8 m-l-10">
<div class=" formError validateAlert" id="alert_to_upload_file_in_vendor_delivery_note_management" >
<div class="formErrorContent" id="test">please Select the .XLSX file <br></div>
<div class="formErrorArrow"></div>
</div>
<input type="file" id="file" name="file2" multiple="multiple" />
<p style="text-align: right; margin-top: 20px;">
<input type="submit" value="Upload Files" name="submit2" class= "btn btn-success" />
</p>
</div>
<div class="col-md-4"></div>
</div>
</div>
</form>
following phpexcel code lines used to upload the file.
$uploadedStatus = 0;
$name2 = '';
if (isset($_POST["submit2"])) {
if (isset($_FILES["file2"])) {
if ($_FILES["file2"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
} else {
if (file_exists($_FILES["file2"]["name"])) {
unlink($_FILES["file2"]["name"]);
$uploadedStatus = 2;
}
$name = basename($_FILES['file2']['name']);
$name2 = explode('.', $name);
if ($name2[count($name2) - 1] == 'csv' || $name2[count($name2) - 1] == 'xlsx') {
$target_path = "uploads/programming/";
$target_location = $target_path . basename($_FILES['file2']['name']);
move_uploaded_file($_FILES["file2"]["tmp_name"], $target_location);
$uploadedStatus = 1;
}
}
} else {
echo "No file selected <br />";
}
}
}
these two working perfectly in separately , no issue with the file upload.
but i need to send some values to the dashboard.php using the same time.
currently before the file is uploading page is redirect to the dashboard.php, any suggestion to submit the form once got $uploadedStatus = 1 where after the file uploading process has completed.
To answer your question, you can use JQuery to upload the file. So the page won't get reload. When you press the upload button show an loading image tells the users that you are working on the upload.
<form action="dashboard.php" method="post" enctype="multipart/form-data" id="form_id">
JQuery & Ajax
function submitForm() {
var formData = new FormData($("#form_id"));
// show your loader image
$.ajax({
url: upload.php,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
// hide your loader image
},
cache: false,
contentType: false,
processData: false
});
}
Note: Formdata won't work on older browsers. There are some fallback for that, read this thread

Uploading file via ajax

i am trying to upload file using ajax.
form enctype="myltipart/form-data" id="pastTest-form" method="POST" action="upload.php">
<div class="feedback-form-inputs col-5">
<div class="input-field">
<select id="type" required>
<option value="quiz">Quiz</option>
<option value="midterm">Midterm</option>
<option value="final">Final</option>
</select>
</div>
<div class="input-field">
<input type="text" id="professor"/>
</div>
<div class="input-field">
<input type="text" id="name"/>
</div>
<div class="input-field">
<input type="file" id="uploaded_file" name="file" accept="" required />
</div>
</div><!-- END feedback-form-inputs -->
<div class="clear"></div>
<input type="submit" value="submit" onclick="submit() />
<div id="upload-status"> </div>
</form>
my function for opening ajax are in the external file.
function addPastTest1(cid){
// form variables
var type = _("type").value;
var professor = _("professor").value;
var name = _("name").value;
var fileSelect = _('uploaded_file');
var status = _('upload-status');
event.preventDefault();
// Update status text.
status.innerHTML = 'Uploading...';
// Get the selected files from the input.
var file = fileSelect.files[0];
var FileName = file.name;
var FileSize = file.size;
var allowed = ["msword", "pdf","pages"];
var found = false;
// check if the extension of the file match the allowed ones
allowed.forEach(function(extension) {
if (file.type.match('application/'+extension)) {
found = true;
}
})
if (FileSize >10204){
status.innerHtml = 'File must be less than 1mb in size';
}
if (found==true){
// Create a new FormData object.
var formData = new FormData();
// Add the file to the request.
formData.append('file', file, FileName);
// Set up the request.
var ajax = ajaxObj("POST", "ajaxResponse.php");
ajax.onreadystatechange = function(){
if (ajaxReturn(ajax)==true){
if (ajax.responseText=='failed'){
status.innerHtml = "failed to upload file";
}
else {
status.innerHtml = 'uploaded';
alert(ajax.responseText);
}
}
}
ajax.send(formData); //ajax.send("f="+formData+"&t="+type+"&p="+professor+"&n="+name+"&cid="+cid+"&fn="+FileName);
}
}
so i am sending formData to the php. but at this point i can not take the file from form data and upload it to the server.
here is my php
// Ajax calls this code to add a past test
if (isset($_FILES['file']){
$file = $_FILES['file'];
$path = 'files/'.$type.'/'.$fileName;
$moveResult = move_uploaded_file($file, $path);
if ($moveResult != true) {
echo "ERROR: File not uploaded. Try again.";
//unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
}
$path = 'files/'.$type.'/'.$fileName;
$sql = "INSERT into past_papers VALUES ('$name', '$type', '$cid', '$professor','$path')";
$query = mysqli_query($db_conx,$sql);
if (mysqli_affected_rows($db_conx)>0){
echo "success";
exit();
}
else {
echo "failed sql";
exit();
}
}
?>
Also i want to grab inputs with the file and process them together. Upload file, and insert inputs into database.
The simplest one I can find. :)
jQuery code
$("#form-id").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "file-to-call.php",
type: "POST",
data: new FormData(this),
cache: false,
processData: false,
success: function(data) {
//handle success
}
});
}));
HTML code
<form name='form1' method='post' enctype='multipart/form-data' id='form-id'>
<input type='submit' id='input' value='Upload' />
</form>

How to preview an image before and after upload?

I am going to preview an image or photo in a form, but it doesn't work and the HTML code looks like this as below:
<form action="" method="post" enctype="multipart/form-data" name="personal_image" id="newHotnessForm">
<p><label for="image">Upload Image:</label>
<input type="file" id="imageUpload"/></p>
<p><button type="submit" class="button">Save</button></p>
<div id="preview">
<img width="160px" height="120px" src="profile pic.jpg" id="thumb" />
</div>
</form>
and incorporated JS code/script below:
<script type="text/jaavascript">
$(document).ready(function(){
var thumb=$('#thumb');
new AjaxUpload('imageUpload',{
action:$('newHotnessForm').attr('action'),
name:'image',
onSubmit:function(file,extension){
$('#preview').addClass('loading');
},
onComplete:function(file,response){
thumb.load(function(){
$('#preview').removeClass('loading');
thumb.unbind();
});
thumb.attr('src',response);
}
});
});
There are 2 main questions on my form:
1. Why doesn't the preview of the image or picture work?
2. How to paste the photo from the form when the save button is clicked, it will go/link to another PHP or PHP page that I created?
Try this: (For Preview)
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
<body>
<form id="form1" runat="server">
<input type="file" onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</form>
</body>
Working Demo here>
meVeekay's answer was good and am just making it more improvised by doing 2 things.
Check whether browser supports HTML5 FileReader() or not.
Allow only image file to be upload by checking its extension.
HTML :
<div id="wrapper">
<input id="fileUpload" type="file" />
<br />
<div id="image-holder"></div>
</div>
jQuery :
$("#fileUpload").on('change', function () {
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof (FileReader) != "undefined") {
var image_holder = $("#image-holder");
image_holder.empty();
var reader = new FileReader();
reader.onload = function (e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[0]);
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Pls select only images");
}
});
On input type=file add an event onchange="preview()"
For the function preview() type:
thumb.src=URL.createObjectURL(event.target.files[0]);
Live example:
function preview() {
thumb.src=URL.createObjectURL(event.target.files[0]);
}
<form>
<input type="file" onchange="preview()">
<img id="thumb" src="" width="150px"/>
</form>
#######################
### the img page ###
#######################
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#f').live('change' ,function(){
$('#fo').ajaxForm({target: '#d'}).submit();
});
});
</script>
<form id="fo" name="fo" action="nextimg.php" enctype="multipart/form-data" method="post">
<input type="file" name="f" id="f" value="start upload" />
<input type="submit" name="sub" value="upload" />
</form>
<div id="d"></div>
#############################
### the nextimg page ###
#############################
<?php
$name=$_FILES['f']['name'];
$tmp=$_FILES['f']['tmp_name'];
$new=time().$name;
$new="upload/".$new;
move_uploaded_file($tmp,$new);
if($_FILES['f']['error']==0)
{
?>
<h1>PREVIEW</h1><br /><img src="<?php echo $new;?>" width="100" height="100" />
<?php
}
?>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#ImdID').attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
img {
max-width: 180px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='file' onchange="readURL(this);" />
<img id="ImdID" src="" alt="Image" />

PHP AJAX Image Upload Example Not Uploading

My code produces no errors on the console. When I click the upload button, nothing happens. There is a post sent to itself, as instructed in the tutorial I used but the image is not uploaded to my folder and it is not displayed on my page. Barring the fact I know I should use jquery (I will make the transition once I get it to upload to the folder) what is wrong with my code?
<?php
if (!empty($_FILES)) {
$name = $_FILES['file']['name'];
if ($_FILES['file']['error'] == 0) {move_uploaded_file($_FILES['file']
['tmp_name'], "post_images/" . $name))}
}
?>
<script type="text/javascript">
var handleUpload = function (event) {
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('file', fileInput.files[1]);
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event){
if (event.lengthComputable)
{
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');
while(progress.hasChildNodes()) {
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) +
'%'));
}
});
request.upload.addEventListener('load',function(event) {
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error', function(event) {
alert('Upload failed');
});
request.open('POST', 'upload.php');
request.setRequestHeader('Cache-Control', 'no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);
};
window.addEventListener('load', function(event) {
var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});
</script>
<div id="uploaded">
<?php
if (!empty($name)) {
echo '<img src="post_images/' . $name . '" width="100" height="100" />';
}
?>
</div>
<div id="upload_progress"></div>
<div>
<form action="" method="post" enctype="multipart/form-data">
<div>
<input type="file" id="file" name="file" />
<input type="submit" id="submit" value="upload" />
</div>
</form>
</div>
There is only one file in a non- multiple file input element, fileInput.files[1] attempts to use the second file.
data.append('file', fileInput.files[0]);

Categories