On drop anywhere on body start upload - dropzone.js

I currently have a dropzone js area like so
<form method="post"
class="dropzone bg-black"
enctype="multipart/form-data"
action="/">
<br>
<div class="normal-form">
<div class="btn d-inline-block btn-previous">
<input class="btn"
id="files"
type="file"
name="image"
multiple="multiple">
</div>
<button class="btn"
style="font-size: 20px;"
type="submit">Upload
</button>
</div>
</form>
And my dropzone js configuration looks like so
<script defer>
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone(".dropzone", {
autoProcessQueue: false
});
myDropzone.on('drop', function (e) {
document.querySelector('#files').files = e.dataTransfer.files;
});
$('form').on('drop', function () {
$('form').submit();
});
$('form').on('submit', function () {
$('form').addClass('hidden');
$('.loader').removeClass('hidden');
});
</script>
As it works, when some one drops a file or files, it hides, shows a upload gif while it uploads the files till uploaded then redirects.
This works fine. The only issue I'm confused about is how do I make it so if they drop anywhere on the body instead of just the dropzone class, to have that work?
I tried doing
var myDropzone = new Dropzone(document.body, {
autoProcessQueue: false
});
but I get
Uncaught Error: No URL provided.
Any help would be appreciated.

Got it, I had to put in the Dropzone config the url action
var myDropzone = new Dropzone(document.body, {
url: "/",
autoProcessQueue: false,
createImageThumbnails: false,
});

Related

Google recaptcha v3 recaptcha_response is null

i am using google recaptcha v3 in my website ,
here is the code i have added in my html web page in the head:
<script src="https://www.google.com/recaptcha/api.js?render=my public key"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('my public key', { action: 'contact' }).then(function (token) {
var recaptchaResponse = document.getElementById('recaptchaResponse');
ecaptchaResponse.value = token;
});
});
</script>
and i added this in my form :
<input type="hidden" name="recaptcha_response" id="recaptchaResponse">
but when i submit the form and try to see the content of $_POST['recaptcha_response'] with var_dump()
it is just an empty string : string(0) ""
where is the mistake ?
thanks for answers !
i tried lots of changes but everytime i get " token = null " then i try this.. 100% working....
in Your Html
<html>
<head>
</head>
<body>
<form id="contact">
<div class="col-12">
<div class="form-group">
<input type="hidden" name="captcha_token" id="recaptchaResponse" data-sitekey="YOUR-SITE-KEY">
</div>
</div>
<div class="col-12">
<button type="submit" class="btn btn-lg" id="submit-btn">
SUBMIT
</button>
</div>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js?onload=ReCaptchaCallbackV3&render=YOUR-SITE-KEY"></script>
</body>
</html>
after then add in your js file
$(document).ready(function(){
setInterval(function(){
ReCaptchaCallbackV3();
}, 90000);
$(document).on("submit",'#contact',function (e) {
var token = $('[name="g-recaptcha-response"]').val();
console.log(token);
});
});
var ReCaptchaCallbackV3 = function() {
grecaptcha.ready(function () {
grecaptcha.execute('YOUR-SITE-KEY', { action: 'contact' }).then(function (token) {});
});
}
In your original script you have a typo:
var recaptchaResponse = document.getElementById('recaptchaResponse');
ecaptchaResponse.value = token;
Instead of recaptchaResponse, you wrote ecaptchaResponse

Django Python can not upload directory with large quantity of files

I am trying to upload a directory with large number of dicom files using Django and JQuery ajax. Each file size is not more than 600kb. I can upload 200 files at a time. If I increase the number of files (tried to upload 14000 files), it doesn’t work. The site gets stuck and it’s not showing any error. Can anyone please help me with this problem? I have attached my code below. Thanks in advance.
View.py:
def handle_uploaded_file(f,filePath):
with open(filePath+'/'+f.name, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
def UploadScanView(request):
if request.method == 'POST':
form = create_scan_form(request.POST)
if form.is_valid():
scan = form.save(commit=False)
scan.project_id = form.cleaned_data.get('project_id')
directory_name = request.POST.get('directories')
json_to_dictionary = json.loads(directory_name)
print(json_to_dictionary)
for upload_file in request.FILES.getlist('file'):
file_path = settings.MEDIA_ROOT+'/'+os.path.dirname(json_to_dictionary[upload_file.name])
print(file_path)
if os.path.exists(file_path):
handle_uploaded_file(upload_file, file_path)
else:
os.makedirs(file_path)
handle_uploaded_file(upload_file,file_path)
return render(request, 'fileupload/basic_upload/scan_upload.html', {'form': form})
else:
form = create_scan_form()
return render(request, 'fileupload/basic_upload/scan_upload.html', {'form': form})
HTML and JQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<script>
/*fileupload div*/
$(document).ready(function(){
$("#my-file").on('change',function(e){ //submit(function(e){
$("#file-wrap p").text('Now click on Upload button');
});
$("#my-form").on('submit',function(e){ //submit(function(e){
files = document.querySelector("#my-file").files;
var directories = {}
for (var file of files) {
file.webkitRelativePath
directories[file.name] = file.webkitRelativePath
}
directories = JSON.stringify(directories);
document.querySelector("#directories").value = directories
var eventType = $(this).attr("method"); // get method type for #my-form
var eventLink = $(this).attr("action"); // get action link for #my-form
//alert(directories);
//////
var formData = new FormData(this);
formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
$.ajax({
headers: { "X-CSRFToken": '{{ csrf_token }}' },
type: eventType,
url: eventLink,
//data: new FormData(this), // IMPORTANt
data: formData,
cache: false,
contentType: false,
processData: false,
// this part is progress bar
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (e) {
if (e.lengthComputable) {
var percentComplete = e.loaded / e.total;
percentComplete = parseInt(percentComplete * 100);
$('.myprogress').text(percentComplete + '%');
$('.myprogress').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
success: function(getResult) {
$('#my-form')[0].reset(); // reset form
$("#file-wrap p").html('Drag and drop file here'); // change wrap message
}
});
e.preventDefault();
});
});
/*fileupload div*/
</script>
<form id="my-form" method="POST" action="{% url 'fileupload:upload_scan' %}" enctype="multipart/form-data"> <!--independentSub-->
{% csrf_token %}
<div id="user_form" class="container">
<div class="form-group col-sm-4" id="project_id">
{{ form.project_id|as_crispy_field }}
</div>
<!--fileupload div-->
<div id="independentSubDiv" class="row">
<div id="file-wrap" class="form-group col-sm-6" >
<p>Drag and drop file here</p>
<input id="my-file" type="file" name="file" multiple webkitdirectory directory draggable="true">
<input type="text" id="directories" name="directories" hidden />
</div>
</div>
<div style="padding-left: initial" id="independentSubDiv" class="form-group col-sm-7" >
<button type="submit" class="btn btn-primary btn-lg btn-block" name="submit_btn" id="submit_btn">Submit</button>
</div>
<div class="progress form-group col-sm-7" style="padding-left: initial" id="progressDiv" >
<div class="progress-bar progress-bar-success myprogress " role="progressbar">0%</div>
</div>
</div>
</form>

Uploaded file is not saving to database

I have created a form where you can upload video files, but I notice that when uploading it, video takes time to upload depending on the size of the file,so to avoid people staring at a screen for a long time waiting for their video to upload I will send them to a page that says "Your video is processing and will be available when ready".The video is indeed saving to the public app folder and also it saves to my aws3 bucket folder as I requested but I noticed that its not saving the file in the database and I don't know why it by passes the database. I am using laravel, ffmpeg to convert and compress videos and ajax. Can someone help me with this. here is my code below
//this the fileupload.blade.php
<div class="container">
<div class="card">
<div class="card-body">
<form method="POST" action="{{ route('fileUploadPost') }}" enctype="multipart/form-data">
#csrf
<div class="form-group">
<input name="file" id="poster" type="file" class="form-control">
<input type="submit" value="Submit" class="btn btn-success">
</div>
</form>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
function validate(formData, jqForm, options) {
var form = jqForm[0];
if (!form.file.value) {
alert('File not found');
return false;
}
}
(function() {
$('form').ajaxForm({
uploadProgress: function(event, position, total, percentComplete) {
window.location.href = "complete";
},
success: function() {
},
complete: function(xhr) {
}
});
})();
</script>
//this is the controller
$request->validate([
'file' => 'required',
]);
$viddy=new Video;
$file = $request->file('file');
$fileName =uniqid().$file->getClientOriginalName();
$request->file->move(public_path('/app'), $fileName);
$name_file=uniqid().'video.mp4';
$ffp=FFMpeg::fromDisk('local')
->open($fileName)
->addFilter(function ($filters) {
$filters->resize(new \FFMpeg\Coordinate\Dimension(640, 480));
})
->export()
->toDisk('s3')
->inFormat(new \FFMpeg\Format\Video\X264('libmp3lame'))
->save($name_file);
$imageName = Storage::disk('s3')->url($name_file);
$viddy->title=$imageName;
$viddy->save();
return response()->json(['success'=>'You have successfully upload file.']);
}

input(file) and input (text) send with one ajax

html
<body>
<form method="post" action="" id="dataForm" enctype="multipart/form-data">
<input type="text" id="textSelector"/>
<input type="file" id="fileSelector"/>
<button name="sub-comfirm" class="btn-selection-content" type="submit" id="sub-comfirm">Send</button>
</form>
</body>
js/ajax
var fileVar = null;// global var to store file info
$(document).ready(function(){
$('#dataForm').on('submit', function(e) {
e.preventDefault();
SendData();
});
$('#fileSelector').on('change',function(ev){
fileVar = null;
fileVar = new FormData();
$.each(ev.target.files, function(key, value)
{
fileVar.append(key, value);
});
});
});
function SendData(){
var formData = new FormData($("#dataForm")[0]);
// should i add the filerVar like this ?
// formData.append("Image", fileVar);
$.ajax({
type: "POST",
url: "checkinput.php",//you need to add this '?files part' to URL
data: formData,// use fileVar here now
cache: false,
processData: false,
// contentType: false,
success:function(data)
{
console.log(data);
console.log("success");
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log("failure");
}
});
}
php
print_r($_POST);
print_r($_FILES);
my intention is to send input(file) and input(text) in one ajax , i can get the input file value if i add ajax data with fileVar , but i cant get my input text value i have no idea why , can anyone tell me what i did wrong ?
var formData = new FormData($("#dataForm")[0]) is the way to get both to one ajax but i cant get any input text value.
anyone can teach me how to make this work ?
I think you need to specify input name attributes:
<body>
<form method="post" action="" id="dataForm" enctype="multipart/form-data">
<input type="text" id="textSelector" name="textSelector"/>
<input type="file" id="fileSelector" name="fileSelector"/>
<button name="sub-comfirm" class="btn-selection-content" type="submit" id="sub-comfirm">Send</button>
</form>
</body>
Hope that helps.

How get the value from a link and send the form using mootools?

I have a such form with many links:
<form name="myform" action="" method="get" id="form">
<p>
My link
</p>
<p>
My link 2
</p>
<p>
My link 3
</p>
<input type="hidden" name="division" value="" />
</form>
I would like to send the form's value from the link that was clicked to php script and get the response (not reloading the page).
I'm trying to write a function that gets the value from a link:
<script type="text/javascript">
window.addEvent('domready', function() {
getValue = function(division)
{
var division;
division=$('form').getElements('a');
}
</script>
but I don't know how to write it in a right way. Next I would like to send the form:
$$('a.del').each(function(el) {
el.addEvent('click', function(e) {
new Event(e).stop();
$('form').submit();
});
});
How I should send it to get the response from a php file not reloading the page?
Instead of putting in javascript inline in the HTML, I would suggest using a delegated event instead. I would also send the form using an ajax call instead of a form submit.
<form id="form">
<a data-value="A">My link</a>
...
</form>
<script>
var formEl = document.id('form');
formEl.addEvent('click:relay(.del)', function() {
var value = this.getProperty('data-value');
new Request.JSON({
url: '/path/to/your/listener',
onSuccess: function(data) {
// ...
}
}).get({
value: value
});
});
</script>
This works for me:
<form id="form">
<a data-value="A">My link</a>
...
</form>
<script>
var links = document.id('form').getElements('a');
links.each(function(link) {
link.addEvent('click', function(e) {
e.stop();
var value = link.getProperty('data-value');
var req = new Request.HTML({
url: "/path/to/your/listener",
data: value,
onRequest: function(){
$('display').set('text', 'Search...');
},
onComplete: function() {
},
update : $('display')
}).get(
{data: value}
);
});
})
</script>

Resources