I'm using Dropzone.js for uploading files, but it behaves strangely. When I open the page, the dropzone form doesn't show up, only the fallback field. When I drag & drop a file into the browser, the browser opens that file, then I use the Back button on the browser and Dropzone form shows up. I tried adding an alert inside the init function and it fires only when I press Back (the second scenario). There are no errors in the console. Here's the code:
<!-- Dropzone -->
<div id="dropzone">
<form action="<?php echo site_url('/settings/upload'); ?>" class="dropzone" id="upload">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</form>
</div>
<!-- Dropzone -->
<script src="<?php echo base_url(); ?>assets/common/theme/scripts/plugins/forms/dropzone/dropzone.min.js"></script>
<script type="text/javascript">
Dropzone.options.upload = {
paramName: "info",
maxFilesize: 0.1,
init: function() {
alert("test");
this.on("error", function(file, msg) {
alert(msg);
});
this.on("success", function(file, msg) {
var data = jQuery.parseJSON( msg );
if (data.success) {
alert("success");
} else {
alert(data.message);
}
});
}
};
</script>
Turned out it was issue with cloudflare rocket loader. Exluded the two <script> statements from it using data-cfasync="false" and it worked.
Related
In a project, I am using a file upload button along with drag and drop file functionality. I am facing problem in a module that is;
After user select the files using input type file button or drop files, A dialog box pops up, which holds a form. I want to send form data and selected/dropped files using ajax to the server. Till now my code is like below;
This code is working fine for input type file button, but How can I achieve the same functionality using drag and drop approach.
user is selecting file.
after files are selected, HTML-5 dialog modal pops up which have a form.
after form submits, the dialog closes automatically(because using form method="dialog).
After the dialog closes, It takes form data from dialog box and input files and passes them to the ajax upload function.
....But facing difficulty for drag and drop files, confused about how to do the same if sometime user drop file and sometime select using input type button??
-----below is the code--------
<html>
<head>
<style>
.droparea{
width:100%;
height: 50vh;
background: pink;
}
</style>
</head>
<body>
<div class="droparea">
<input type="file" name="user_files" multiple />
</div>
<dialog id="user_detail_dialog">
<form method="dialog" id="user_detail_form_dialog">
<input type="text" name="user_name" placeholder="Your Name" />
<input type="number" name="user_age" placeholder="Your Age" />
<button type="submit">Submit Form</button>
</form>
</dialog>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var user_details_dialog_box = document.getElementById('user_detail_dialog');
$("input[type='file']").on("change", function(ev) {
ev.preventDefault();
user_details_dialog_box.showModal();
});
user_details_dialog_box.addEventListener('close', () => {
var form_data = new FormData(document.getElementById('user_detail_form_dialog')); //appending user entered details in the dialog form
form_data.append('files[]', document.querySelector('input[type=file]').files); //appending all files selected by user.
send_data(form_data);
})
</script>
<script>
function send_data(form_data){
$.ajax({
url: "http://127.0.0.1:5000/upload",
type: "POST",
data: form_data,
contentType: false,
cache: false,
dataType: 'json',
processData:false,
withCredentials:true,
beforeSend: function(xhr) {
},
xhr: function() {
var xhr = $.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener('progress', function(event){
var percent = 0;
if (event.lengthComputable) {
percent = Math.ceil(event.loaded / event.total * 100);
}
console.log(percent)
}, false);
}
return xhr;
},
success: function (msg) {
console.log(msg)
},
error: function(data){
console.log(data);
}
});
}
</script>
</body>
</html>
I'm trying to upload multiple files with progress bars to show how much of the file has been uploaded. For some reason the files are not being uploaded and the progress bars only work for one upload. Please help me alter the code to work.
$('.btnUpload').click(function(){
//submit all form
$('form').submit();
});
$(document).on('submit','form',function(e){
e.preventDefault();
$form = $(this);
uploadImage($form);
});
function uploadImage($form){
alert("in");
$form.find('.progress-bar')
var formdata = new FormData($form[0]); //formelement
var request = new XMLHttpRequest();
//progress event...
request.upload.addEventListener('progress',function(e){
var percent = Math.round(e.loaded/e.total * 100);
$form.find('.progress-bar').width(percent+'%').html(percent+'%');
});
//progress completed load event
request.addEventListener('load',function(e){
$form.find('.progress-bar').html('upload completed....');
});
request.open('post', 'upload.php');
request.send(formdata);
$form.on('click','.cancel',function(){
request.abort();
$form.find('.progress-bar')
.html('upload aborted...');
});
}/*
function uploadFile(){
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
success: function(data){
$("#gallery").html(data);
},
xhrFields: {
// add listener to XMLHTTPRequest object directly for progress (jquery doesn't have this yet)
onprogress: function (progress) {
// calculate upload progress
var percentage = Math.floor((progress.total / progress.totalSize) * 100);
// log upload progress to console
console.log('progress', percentage);
if (percentage === 100) {
console.log('DONE!');
}
}
},
processData:false,
error: function(){}
});
}));
});
}*/
<html>
<head>
<title>PHP AJAX Multiple Image Upload</title>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<SCRIPT SRC="upload.js"></SCRIPT>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="gallery-bg">
<form id="uploadForm" action="" method="post">
<div id="gallery">No Images in Gallery</div>
<div id="uploadFormLayer">
<p class="txt-subtitle">Upload Multiple Image:</p>
<p><input name="userImage[]" type="file" class="inputFile" /><p>
<div class="progress">
<div class="progress-bar" style="width:0%"></div>
</div>
<p><input name="userImage[]" type="file" class="inputFile" /><p>
<div class="progress">
<div class="progress-bar" style="width: 0%;">
</div>
</div>
<p><input name="userImage[]" type="file" class="inputFile" /><p>
<div class="progress">
<div class="progress-bar" style="width: 0%;">
</div>
</div>
<p><input type="submit" value="Submit" class="btnUpload" /></p>
</div>
</form>
</div>
<!-- begin snippet: js hide: false -->
</body>
</html>
This is not an answer to your question, but perhaps a solution to your problem.
What you posted sends the files to the server, but once they get there they are kept in a sandbox -- they must be "handled" once they get there or they won't be stored. Therefore, you must write a processor app in your back-end language (PHP or ASP.Net or etc.) to process the files (validate them, move them to the folder they are supposed to be in, etc.).
If your back-end is PHP, would you consider switching to Ravishanker Kusuma's jQuery Upload File Plugin? I've tried a bunch of file upload plugins and found Ravi's the best. Use it in all my projects. Try his example (link above) - it's dead simple.
1) Include the Hayageek scripts
2) Add a div, which becomes the dynamic upload button/fields
<div id="fileuploader">Upload</div>
3) Add this jQuery code:
$("#fileuploader").uploadFile({
url:"name_of_your_php_file_that_receives_the_files.php",
fileName:"myfile" //you will use this varname in the php file
});
That PHP file will look something like this:
<?php
$output_dir = "uploads/";
if(isset($_FILES["myfile"])) {
$ret = array();
if(!is_array($_FILES["myfile"]["name"])) {
//just one file
$fileName = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);
$ret[]= $fileName;
}
else //Multiple files, file[]
{
$fileCount = count($_FILES["myfile"]["name"]);
for($i=0; $i < $fileCount; $i++)
{
$fileName = $_FILES["myfile"]["name"][$i];
move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$fileName);
$ret[]= $fileName;
}
}
echo json_encode($ret);
}
?>
I have an upload button on my main page that submits to a php form, then returns the image back to the main page. What I am trying to do now is get the image element to load to an Iframe in the parent page as a variable that I can put in a div. Everything is functioning properly until the image will not display in the part of the Iframe, I think I am close but cannot see what is wrong in my code.
index.html
just the javascript , iframe, and id where the messages appears
<script type="text/javascript">
function updatepicture(pic) {
document.getElementById("image").setAttribute("src", pic);
$("#iFrameThingy").contents().find("#message").attr("src","photos/cw/briantest/" +pic);
}
</script>
<iframe id="iFrameThingy" src="Templates/template2/index.html" width="100%" height="4500" name="search_iframe"></iframe>
<p id="message">Upload message will go here.</p>
iframe.html
<script type="text/javascript">
function updatepicture(pic){
document.getElementById("image").setAttribute("src",pic);
}
</script>
--> Where I am trying to place the image
<div class="caption2">
<img id="productImage" id="images/product.png"alt="Product" height="416" width="417">
</div>
I had this working at one point but mistakenly changed something and now it is not working but I know I am close. Any help is appriciated
upload.php
<?php
if ($_FILES['file']['size'] > 0) {
if ($_FILES['file']['size'] <= 153600) {
if (move_uploaded_file($_FILES['file']['tmp_name'], "images/".$_FILES['file']["name"])) {
// file uploaded
?>
<script type="text/javascript">
parent.document.getElementById("message").innerHTML = "";
parent.document.getElementById("file").value = "";
window.parent.updatepicture("<?php echo 'images/'.$_FILES['file']["name"]; ?>");
</script>
<?php
} else {
// the upload failed
?>
<script type="text/javascript">
parent.document.getElementById("message").innerHTML = "<font color='#ff0000'>There was an error uploading your image. Please try again later.</font>";
</script>
<?php
}
} else {
// the file is too big
?>
<script type="text/javascript">
parent.document.getElementById("message").innerHTML = "<font color='#ff0000'>Your file is larger than 150kb. Please choose a different picture.</font>";
</script>
<?php
}
}
?>
index.html (submit form)
<form id="form" method="post" action="upload.php" enctype="multipart/form-data" target="iframe">
<input type="file" id="file" name="file" />
<input type="submit" name="submit" id="submit" value="Upload File" />
Upload message will go here.
Change this line:
document.getElementById("image").setAttribute("src",pic);
to this:
document.getElementById("productImage").setAttribute("src",pic);
And change this:
<img id="productImage" id="images/product.png"alt="Product" height="416" width="417">
to this:
<img id="productImage" alt="Product" height="416" width="417">
You are using incorrect id there:
$("#iFrameThingy").contents().find("#message").attr("src","photos/cw/briantest/" +pic);
You should use productImage instead of message. Use this:
$("#iFrameThingy").contents().find("#productImage").attr("src","photos/cw/briantest/" +pic);
I want to upload image from popup but not getting proper solution.
what i wanted to do
1. On button click open popup
2. In that popup open form for browse image
3. After uploading image i want to show image in same popup and user can crop it
4. After completed cropping save image to database and folder and want to show profile pic
What i did
1.I have completed all code in core php but without using popup
for popup
2. I can open popup on button click, browse file and action goes to controller.
Code
View page
// open popup
<div class="profile-pic fl">
<div class="txtc">
<?php echo $this->tag->image(array("img/profile_pic_default.jpg","class"=>"profile_img")) ; ?>
</div>
<div class="txtc mrgt2">
<button id="openPopup" onclick="upload_action();">Upload Image</button>
</div>
</div>
//iamge upload form
<div id="up-image" style="display: none">
<div style="margin:0 auto; width:600px">
<div id="thumbs" style="padding:5px; width:600px"></div>
<div id="crop-image" style="width:600px">
<?php echo $this->tag->form(array("personaldetails/uploadImage","id"=>"cropimage",'enctype'=>"multipart/form-data"))?>
Upload your image <input type="file" name="photoimg" id="photoimg" />
</form>
</div>
</div>
Script to open popup and send data
<script type="text/javascript">
$(document).ready(function() {
$edit_dialog = $("#up-image").dialog({
autoOpen:false,
title:"Upload image",
modal:true,
height: 300,
width: 600,
buttons:[
{text: "Submit", click: function() { $('form',$(this)).submit(); }},
{text: "Cancel", click: function() { $(this).dialog("close"); }}
],
create: function(event, ui)
{
$(this).parents(".ui-dialog").css("margin-left", 350);
$(this).parents(".ui-dialog").css("margin-top", 50);
}
});
//Submit action for dialog form
$("#up-image form").submit(function() {
var formData = new FormData($('form')[0]);
$.post($(this).attr('action'), $(this).serialize(),function(formData)
{
alert('done'+data);
$("#up-image").dialog('close');
},'json');
//stop default form submit action
return false;
});
//attach action to edit links
});
function upload_action()
{
$edit_dialog.dialog('open');
}
Controller action
public function uploadImageAction()
{
echo "<pre>";print_r($_FILES);echo "<pre>";exit; // not able to get request
}
You can use jcrop plugin for that:
http://deepliquid.com/projects/Jcrop/demos/crop.php
http://deepliquid.com/content/Jcrop.html
For fullfill your requirement you have to use:
AjaxUpload and JCrop together.
Ajaxupload will upload image to server and jcrop helps you to crop image.
After croppping you have to need old image and save cropped image in DB and folder.
add form in a hidden div and set position absolute or fixed
animate or fade in hidden div on-clik function
set z-index for div ordering
I tried one of the examples here to load the content in the div, but apart from displaying the image, it doesn't show anything. Where I'm going wrong?
File ajax1.js:
function General_Refresh(url,div){
//Showing the load image (pay attention to /> of <img
document.getElementById(div).setInnerXHTML('<span id="caric"><center><img src="http://website.name/images/ajax-loader.gif" /></center></span>');
var ajax = new Ajax();
ajax.responseType = Ajax.FBML;
ajax.ondone = function(data) {
//Hide the loading image
document.getElementById('caric').setStyle('display','none');
document.getElementById(div).setInnerFBML(data);
}
//If there are errors re-try
ajax.onerror = function() {
General_Refresh(url,div);
}
ajax.post(url);
}
File quote.html:
<script src="http://website.name/scripts/ajax1.js" type="text/javascript"></script>
<script type="text/javascript">
<!--
General_Refresh("http://website.name/quote.php","quote");
//-->
</script>
<div id="wrapper">
<div id="quote"><strong>this</strong></div>
</div>
</div>
There was nothing wrong with FBJS/Ajax. It was an error in quote.php.