html upload file(image) in one click - php

I'd like to upload a file in one click, so I tried to combine two click events in one, but the $_FILE variable does not load the image, here's my code :
<form target='_self' action='upload.php' method='post' enctype='multipart/form-data'>
<div class = 'testocentrato'>
<input style='display:none' type='file' accept='.jpg' name='file' id='file'/>
<input style='display:none' type='submit' id='caricaimmagine' name='caricaimmagine' />
<input class='inputfile' type='button' value='Scegli file da PC' onclick='document.getElementById('file').click(); document.getElementById('caricaimmagine').click();' />
<input style='display:none' type='submit' />
<input class='inputfile' type='submit' name='eliminaimmagine' onclick='document.getElementById('eliminaimmagine').click();' value='".$lang['TASTO_ELIMINA_FOTO']."' />
<input type='hidden' name='id_utente' value='".$user['id']."' />
</form>

It is possible to upload images with one click with ajax, check https://makitweb.com/how-to-upload-image-file-using-ajax-and-jquery/.
here is my html code I used the label tag so when I click the upload icon the select file windows will appear.
<form method="post" enctype="multipart/form-data">
<label class='foto' for="imgid">
<img id="photo" src="images/photo.png">
<p>Foto</p>
</label>
<input type="file" value="chosen File" id="imgid" name="img" accept="image/*">
<img class="previewimg" src="" width="100" height="100">
<span id="showImagePath" ></span>
<button class="btn btn-primary" id="toPost">Post</button>
</form>
mycss.
#imgid{
display:none;
}
.foto{
float:left;
}
.previewimg{
display:none;
background-color:grey;
}
#imgToPost{
display:none;
}
my Jquery:
I used setInterval() function to make my script run until the image is selected that way is going to be uploaded and the name and the image can be previewed.
$("#photo").click(function(){
setInterval(function(){
var fd = new FormData();
var files = $('#imgid')[0].files;
// Check file selected or not
if(files.length > 0 ){
$(".previewimg").show();
fd.append('file',files[0]);
$.ajax({
url: 'action.php?action=postcontentimage',
type: 'post',
data:fd,
contentType: false,
processData: false,
success: function(result){
var name ="";
if(result != 0){
$(".previewimg").attr("src", result).show();
for(var i=0; i < result.length;i++){
if(i>8){
name += result[i];
}
$("#showImagePath").html(name);
clearInterval();
}
}
}
})
}else{
alert("no image has been selected");
}
}, 2000);
})
my PHP:
<?php
if(isset($_FILES['file']['name'])){
/* Getting file name */
$filename = $_FILES['file']['name'];
/* Location */
$location = "uploads/".$filename;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);
$imageFileType = strtolower($imageFileType);
/* Valid extensions */
$valid_extensions = array("jpg","jpeg","png");
$response = 0;
/* Check file extension */
if(in_array(strtolower($imageFileType), $valid_extensions)) {
/* Upload file */
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
$response = $location;
}
}
echo $response;
exit;
}else{
echo 0;
}
?>

Because you are directly clicking on submit before secting the file.
Remove
document.getElementById('caricaimmagine').click();
You need to click that button manually.

Related

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 access my uploaded images via Wordpress Media Uploader?

It is my first time trying to use Wordpress Media Uploader inside my theme but I am having difficulties accessing my uploaded images. Here is the problem: I can upload my images but I don't know how to retrieve them. For example when i click my upload button it uploads my image but my textfield is blank (it should display path to my uploaded image) so I can use it inside my theme like so :<?php echo $options['body_background'];?>
My functions inside options-page.php look's like this:
//Heading Text (works fine and i can echo value out...)
function text_heading_setting(){
$options = get_option('plugin_options');
$get_options = $options['text_heading'];
echo '<input type="text" name="plugin_options[text_heading]" value="'.$get_options.'" >';
}
//Menu Image upload field (can upload image but can't echo its path)
function body_background_setting(){
$options = get_option('plugin_options');
$get_options_menu = $options['menu_background'];
echo '<div class="uploader">
<input type="text" name="plugin_options[menu_background]" id="menu_image_bg" value="'.$get_options_menu.'" />
<input class="button" name="_unique_name_button" id="_unique_name_button" value="Upload" />
</div>';
}
//Body Image upload field (can upload image but can't echo its path)
function body_background_setting(){
$options = get_option('plugin_options');
$get_options_body_bg = $options['body_background'];
echo '<div class="uploader">
<input type="text" name="plugin_options[body_background]" id="menu_image_bg" value="'.$get_options_body_bg.'" />
<input class="button" name="_unique_name_button" id="_unique_name_button" value="Upload" />
</div>';
}
Uploader js looks like this:
jQuery(document).ready(function($){
var _custom_media = true,
_orig_send_attachment = wp.media.editor.send.attachment;
$('.button').click(function(e) {
var send_attachment_bkp = wp.media.editor.send.attachment;
var button = $(this);
var id = button.attr('id').replace('_button', '');
_custom_media = true;
wp.media.editor.send.attachment = function(props, attachment){
if ( _custom_media ) {
$("#"+id).val(attachment.url);
} else {
return _orig_send_attachment.apply( this, [props, attachment] );
};
}
wp.media.editor.open(button);
return false;
});
$('.add_media').on('click', function(){
_custom_media = false;
});
});
Screenshot of my problem:
http://vasinternetposao.com/wordpressdevelopment/imgupload.png
Can someone help me out so I can access my uploaded images?
try adding esc_url() to the value
//Menu Image upload field (can upload image but can't echo its path)
function body_background_setting(){
$options = get_option('plugin_options');
$get_options_menu = $options['menu_background'];
echo '<div class="uploader">
<input type="text" name="plugin_options[menu_background]" id="menu_image_bg" value="'.esc_url($get_options_menu).'" />
<input class="button" name="_unique_name_button" id="_unique_name_button" value="Upload" />
</div>';
}
//Body Image upload field (can upload image but can't echo its path)
function body_background_setting(){
$options = get_option('plugin_options');
$get_options_body_bg = $options['body_background'];
echo '<div class="uploader">
<input type="text" name="plugin_options[body_background]" id="menu_image_bg" value="'.esc_url($get_options_body_bg).'" />
<input class="button" name="_unique_name_button" id="_unique_name_button" value="Upload" />
</div>';
}

$_FILES array is empty

This is the first time I am trying to upload a file and for some reason my $_FILES array is empty. I have checked again and again my HTML and it looks okay to me. When i try to debug the below code in eclipse the $_Files array is empty when i check it. I have checked the php_ini file it has:
file_uploads = On
upload_max_filesize = 2M
The form is in a fancybox modal window.
My HTML looks like this:
<form action="/CiREM/attachments/addAttachmentsModal.php?requestId=120" enctype="multipart/form-data" method="post" id="addattachment" name="addattachment" class="form-vertical" autocomplete="off">
<input type='hidden' id='requestId' name='requestId' value="120"/>
<input type='hidden' id='listScreen' name='listScreen' value=""?>
<input type='hidden' name='MAX_FILE_SIZE' value='4000000' /><br/> <strong>Max File size Allowed: </strong>4 Mb <br/><strong>File Formats Allowed: </strong>gif,jpeg,jpg,png<br/><hr/> <div class="control-group">
<div class="controls input">
<input class="input-file" type="file" name="upload_file[]" id="upload_file[]"/><br/>
</div>
</div>
<input class="input-file" type="file" name="upload_file[]" id="upload_file[]"/><br/>
</div>
</div>
</div>
<div class ="clear"></div>
<input id="addAttachmentsBtn" type="submit" class="btn btn-primary btn-large" value="Add Attachments"/>
</form>
My php is
<form action="<?php echo $_SERVER['PHP_SELF']."?requestId=".$requestId?>" enctype="multipart/form-data" method="post" id="addattachment" name="addattachment" class="form-vertical" autocomplete="off">
<input type='hidden' id='requestId' name='requestId' value="<?php echo $requestId;?>"/>
<input type='hidden' id='listScreen' name='listScreen' value="<?php echo $listScreen;?>"?>
<?php
if ($CIREM['MAX_IMG_NUM']>0){
echo "<input type='hidden' name='MAX_FILE_SIZE' value='".$CIREM['MAX_IMG_SIZE']."' />";
echo "<br/> <strong>Max File size Allowed: </strong>".($CIREM['MAX_IMG_SIZE']/1000000)." Mb <br/><strong>File Formats Allowed: </strong>".$CIREM['IMG_TYPES']."<br/><hr/>";?>
<?php for ($i=1;$i<=$CIREM['MAX_IMG_NUM'];$i++){?>
<div class="controls input">
<input class="input-file" type="file" name="upload_file[]" id="upload_file[]"/><br/>
</div>
<?php }?>
<?php }
else{
echo "<p class='alert alert-info'>Attachment uploading is not allowed</p>";
}
?>
Any help will be greatly appreciated.
Thanks,
Shakira
Without looking through that spaghetti code, first check whether your $_POST is also empty.
If it is, make sure that post_max_size is larger than upload_max_filesize. The two settings have to be congruent.
First of all sorry for the late reply but since sometimes people stumble upon old topics on stackoverflow, I decided to write the way it works for me.
So, to send files via ajax you have to use FormData.
I'll paste a link to a github project I have to submit forms via ajax so you can check the working example and paste here the snippet.
Link: https://github.com/pihh/auto-ajax-form
Code:
$( "form" ).on('submit',function( event ) {
if($(this).attr('ajax')){
event.preventDefault();
var marianaFormUrl = $(this).attr('action');
var marianaFormId = $(this).attr('id');
var marianaFormMethod = $(this).attr('type');
var marianaFormSucess = $(this).attr('success');
var marianaFormComplete = $(this).attr('complete');
var marianaFormBefore = $(this).attr('before');
var marianaFormInputs = $('#' + marianaFormId +' :input');
var marianaEncType = $(this).attr('enctype');
var marianaFormData = {};
// Set enctype
if(marianaEncType === undefined || marianaEncType == ''){
$(this).attr('enctype','multipart/form-data');
}
// Run Ajax Call
$.ajax({
url: marianaFormUrl,
type: marianaFormMethod,
dataType: 'JSON',
data: new FormData( this ),
processData: false,
contentType: false,
cache: false,
success:function(data){
// Run success
if(marianaFormSucess !== undefined && marianaFormSucess !== ''){
var fn = marianaFormSucess;
var func = fn +'( data )';
eval(func);
}
},
complete:function(data){
// Run complete
if(marianaFormComplete !== undefined && marianaFormComplete !== ''){
var fn = marianaFormComplete;
var func = fn +'( data )';
eval(func);
}
}
});
}
});
This is it, using formData it sends the files just fine.

Ajax Upload error

This file index
<form name="classupload" method="post" enctype="multipart/form-data" action="">
<h3>Select pictures: </h3><br />
<input type="file" name="Filedata[]" style="margin-top:2px;"/><br />
<input type="file" name="Filedata[]" style="margin-top:2px;"/><br />
<input type="file" name="Filedata[]" style="margin-top:2px;"/><br />
<input type="file" name="Filedata[]" style="margin-top:2px;"/><br />
<input type="file" name="Filedata[]" style="margin-top:2px;"/><br />
<div id="viac"></div>
<div style="margin-top:4px;"><a onclick="multiupload();">More</a><br /></div>
<input type="submit" value="Upload" id="classupload"/>
</form>
And file javascript
jQuery(document).ready(function() {
$("#classupload").click(function() {
var xleng=document.classupload.elements['Filedata[]'].length;
dv = document.createElement("div");
for (var i = 0; i < xleng ; i++)
{
img=document.classupload.elements['Filedata[]'][i].value;
if(img.toString().length > 1){
$.ajax({
type: "POST",
url: "upload.php",
data: img,
success: function(data_response) {
dv.innerHTML = i + ' - ' + data_response;
}
});
}
}
responseStatus("Done!");
document.getElementById("result").appendChild(dv);
return false; // avoid to execute the actual submit of the form.
})
});
And file upload.php
if ($_REQUEST['Filedata']) {
}
Please help me write file upload.php display file
because Instead of the file being uploaded, I get nothing ,Please HELP ?
You can't upload files via AJAX directly. You need a plug-in that uses a hidden Iframe or makes use of HTML5 features.

Categories