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);
}
?>
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 am trying to implement the PanZoom JS Functionality in my Code. The Code works fine when I add the static Image to the The WebPage and add the PanZoom Function to it.
Eg:
>>HTML
<div class="imageSection">
<div class="image-box" id="targetLayer">
<img id="scene" class="image-preview" src="uploads/Jack-Ceph.jpg" class="upload-preview" />
</div>
</div>
>>JS
var element = document.getElementById('scene')
panzoom(element,{
maxZoom: 5,
minZoom: 0.5,
transformOrigin: {x: 0.5, y: 0.5}
})
But the Problem is that When I add the Image dynamically using the Jquery POST method and PHP The PanZoom JS stops working.
The Code I tried for adding the Image dynamically is :
HTML
<form id="uploadForm" action="upload.php" method="post" enctype="multipart/form-data">
<input id="picture" name="picture" type="file" >
<p>Drag your files here or click in this area.</p>
<button id="upload" name="upload" type="submit">Upload</button>
</form>
JS
// Upload image using Ajax
$(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,
processData:false,
success: function(data)
{
$("#targetLayer").html(data);
},
error: function()
{
}
});
}));
});
Upload.php
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['picture']['tmp_name'])) {
$sourcePath = $_FILES['picture']['tmp_name'];
$targetPath = "uploads/".$_FILES['picture']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
?>
<img id="scene" class="image-preview" src="<?php echo $targetPath; ?>" class="upload-preview" />
<?php
}
}
}
So When I run the above code, i get the error :
Uncaught Error: Cannot create panzoom for the current type of dom
element
at createPanZoom
and the Panzoom effect doesn't work.
I have Implemented the drag and drop file upload using the plugin Filedrop.js on asp.net web application.I need the properties of the files before uploading it.
How can I get the properties of file once the file dropped into the browser before uploading the file? I need these properties from the IE9, IE8 and IE7 browsers.
<body>
<div id="zone" class="upload">
<div id="dropIE9" class="drop" style="text-align: center; margin-bottom: 10px;">
Drop or Upload
CSV File
<br />
<a>Browse</a>
<br />
<input id="fileCsvUploadIE9" type="file" style="opacity: 0; display: block;" />
</div>
</div>
<script type="text/javascript">
var options = { iframe: { url: 'FileUploadHandler.ashx'} };
var zone = new FileDrop('zone', options);
zone.event('send', function (files) {
files.each(function (file) {
file.event('done', function (xhr) {
alert('Done uploading ' + this.name + ', response:\n\n' + xhr.responseText);
});
file.sendTo('FileUploadHandler.ashx');
});
});
zone.event('iframeDone', function (xhr) {
alert('Done uploading via <iframe>, response:\n\n' + xhr.responseText);
});
fd.addEvent(fd.byID('multiple'), 'change', function (e) {
zone.multiple(e.currentTarget || e.srcElement.checked);
});
</script>
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.
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.