Preview with fineuploader not working when using manual trigger - fine-uploader

I can't get the preview working with the fineuploader when using the manual triggering , I have put the drawthumbnail into the submit and submitted event but nothing works. I am using one of the stackoverflow examples as a base. I am sure that the event is triggered as the log fires:
[FineUploader 4.1.0] Attempting to update thumbnail based on server response.
[FineUploader 4.1.0] Rendering template in DOM.
[FineUploader 4.1.0] Template rendering complete
[FineUploader 4.1.0] Received 1 files or inputs.
On submit
Calling draw thumbnail on id: 0 with filename: 2013-01-06 17.14.37.jpg
On submitted
Calling draw thumbnail on id: 0 with filename: 2013-01-06 17.14.37.jpg
$('#myFineUploaderContainer').fineUploader({
debug: true,
template: "qq-simple-thumbnails-template",
thumbnails: {
placeholders: {
waitingPath: "/static//img/loading.gif",
notAvailablePath: "/static//img/loading.gif"
}},
request: {
endpoint: '/ajaxuploadmms',
params: {
'csrf_token': 'XXXXX',
'csrf_name': 'csrfmiddlewaretoken',
'csrf_xname': 'X-CSRFToken',
},
customHeaders: {
'X-CSRFToken': 'XXXXX',
'test': 'test',}},
autoUpload: false,
validation: {
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png']
},
showMessage: function(message) {
// Using Bootstrap's classes
$('#myFineUploaderContainer').append('<div class="alert alert-error">' + message + '</div>');
}
}).on('upload', function(event, id, name) {
var enteredMessage = $('#message').val();
var group = $('.dropdown-menu li a').val();
$(this).fineUploader('setParams', {'group': window.group,'message': enteredMessage, 'csrfmiddlewaretoken': 'XXXXX'}, id);
}).on('submit', function (event, id, filename) {
console.log('On submit');
console.log('Calling draw thumbnail on id: ' +id+ ' with filename: ' +filename );
$(this).fineUploader("drawThumbnail", id, document.getElementById('picture'), 200, false);
}).on('submitted', function (event, id, filename) {
console.log('On submitted');
console.log('Calling draw thumbnail on id: ' +id+ ' with filename: ' +filename );
$(this).fineUploader('drawThumbnail', id, document.getElementById('picture'), 200, false);
}).on('complete', function (event, id, name, response) {
console.log('Complete callback called on id: '+id+'. Response was: '+JSON.stringify(response));
//remove active class from progress bar. remove cancel button from filename
$fileItem = $(this).fineUploader("getItemByFileId", id);
$fileName = $(this).fineUploader("getName", id);
if (response.success) {
$fileItem.find(".progress").removeClass("active").removeClass("progress-info").removeClass("progress-striped").addClass("progress-success");
$fileItem.find(".qq-upload-cancel").remove();
$fileItem.find(".qq-upload-status-text").addClass("green-text");
$fileItem.find(".qq-upload-status-text").html("- Completed");
}
if (response.error) {
$fileItem.find(".progress").removeClass("active").removeClass("progress-info").removeClass("progress-striped").addClass("progress-danger");
$fileItem.find(".bar").removeClass("bar-success").addClass("bar-danger");
$fileItem.find(".qq-upload-cancel").remove();
$fileItem.find(".qq-upload-status-text").addClass("red-text");
$fileItem.find(".qq-upload-status-text").html("- Upload failed!");
$("#fineUploader").prepend('<div id="flashMessage" class="alert alert-error"><button type="button" class="close" data-dismiss="alert">×</button><p>Upload failed on <b>'+$fileName+'</b>! Please try uploading it again.</p></div>');
}
//check to see if there are any uploads happening still. if not, reload the page use getInProgress() API call
$uploadingFiles = $(this).fineUploader("getInProgress");
//close the modal if no uploads are in progress. refresh media index. pop up success banner.
if ($uploadingFiles < 1) {
//uploads_done();
}
});
$('#uploadSelectedFiles').click(function() {
$('#myFineUploaderContainer').fineUploader('uploadStoredFiles');
});
});
</script>
<script type="text/template" id="qq-simple-thumbnails-template">
<div class="qq-uploader-selector qq-uploader">
<div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>
<span>Drop files here to upload</span>
</div>
<div class="qq-upload-button-selector qq-upload-button">
<div>Upload a file</div>
</div>
<span class="qq-drop-processing-selector qq-drop-processing">
<span>Processing dropped files...</span>
<span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>
</span>
<ul class="qq-upload-list-selector qq-upload-list">
<li>
<div class="qq-progress-bar-container-selector progress">
<div class="qq-progress-bar-selector progress-bar"></div>
</div>
<span class="qq-upload-spinner-selector qq-upload-spinner"></span>
<img class="qq-thumbnail-selector" qq-max-size="100" qq-server-scale>
<span class="qq-edit-filename-icon-selector qq-edit-filename-icon"></span>
<span class="qq-upload-file-selector qq-upload-file"></span>
<input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">
<span class="qq-upload-size-selector qq-upload-size"></span>
<a class="qq-upload-cancel-selector qq-upload-cancel" href="#">Cancel</a>
<a class="qq-upload-retry-selector qq-upload-retry" href="#">Retry</a>
<a class="qq-upload-delete-selector qq-upload-delete" href="#">Delete</a>
<span class="qq-upload-status-text-selector qq-upload-status-text"></span>
</li>
</ul>
</div>
</script>
</div>
EDITED:
I have chrome and this is the supported features
qq.supportedFeatures
Object {uploading: true, ajaxUploading: false, fileDrop: false, folderDrop: false, chunking: false…}
ajaxUploading: false
canDetermineSize: false
chunking: false
deleteFileCors: false
deleteFileCorsXdr: false
deleteFileCorsXhr: false
fileDrop: false
folderDrop: false
folderSelection: true
imagePreviews: false
imageValidation: false
itemSizeValidation: false
pause: false
progressBar: false
resume: false
uploadCors: true
uploadCustomHeaders: false
uploadNonMultipart: false
uploadViaPaste: false
uploading: true
__proto__: Object

There is no element in your markup with an ID of "picture", though you are asking Fine Uploader to render the thumbnail to this element. Also, the markup in your question is invalid. You have a closing div without an opening div.

Related

Why my page gets refresh while deleting image on 'product edit page'?

VIEW FILE
<div class="col-sm-4">
<label>Other Images</label>
<div class="input-group control-group img_div form-group" >
<input type="file" name="image[]" class="form-control">
<div class="input-group-btn">
<button class="btn btn-success btn-add-more" type="button">Add</button>
</div>
</div>
</div>
<div>#foreach($image as $image)
<p><img src="{{asset('/files/'.$image->images)}}" height="50px" id="{{$image->id}}" class="photo"/>
<button class="removeimg" data-id="{{$image->id}}" data-token="{{ csrf_token() }}">Remove</button></p>
#endforeach
</div>
AJAX
$(document).ready( function () {
$(document).on('click', '.removeimg',function(){
var confirmation = confirm("are you sure to remove this record?");
if (confirmation) {
var id = $(this).data("id");
// console.log(id)
var token = $(this).data("token");
var $obj = $(this);
$.ajax(
{
url: "{{ url('image/delete') }}/"+id,
type: 'post',
dataType: "JSON",
data: {
"id": id,
"_token": token,
},
success: function (res)
{
// $(this).parents('.photo').remove();
$obj.parents('.photo').remove();
console.log("it Work", res);
}
});
console.log("It failed");
}
});
});
CONTROLLER
public function imgdelete($id){
Image::find($id)->delete($id);
return response()->json([
'success'=> 'Image deleted successfully!'
]);
}
When I delete the image, page gets redirected to product listing. Page should not get refresh when I delete the image. Can you please help me with correction?? NOTE: This process takes place on editproduct page.
You can prevent the default event for the button:
$(document).on('click', '.removeimg',function(event){
event.preventDefault();
.....
});

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>

How to attach onClick events to preview image in vue-dropzone-component

I have components dropzone on vue. Im install my template in settings.
Then i want to set v-on:click(method) to preview image in dropzone, but event don`t works. How to set correctly click to element?
<template>
<vue-dropzone :options="dropzoneOptions" ref="myVueDropzone" id="customdropzone"
:preview-template="template">
</vue-dropzone>
</template>
methods: {
template () {
return `<div class="dz-preview dz-file-preview" v-on:click.native="alert(1)">
<div class="dz-image" v-on:click="alert(1)">
<img data-dz-thumbnail>
</div>
<div class="dz-details" v-on:click="alert(1)">
<div class="dz-size"><span data-dz-size></span></div>
<div class="dz-filename"><span data-dz-name></span></div>
</div>
<div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>
<div class="dz-error-message"><span data-dz-errormessage></span></div>
<div class="dz-success-mark"><i class="fa fa-check"></i></div>
<div class="dz-error-mark"><i class="fa fa-close"></i></div>
</div>`
;
},
}
data: function () {
return {
dropzoneOptions: {
url: 'https://httpbin.org/post',
thumbnailWidth: 200,
maxFilesize: 0.5,
addRemoveLinks: true,
previewTemplate: this.template(),
headers: {"My-Awesome-Header": "header value"},
},
salonID: 0,
photos: [],
}
},

Laravel Image Upload using ajax 500 Internal Server Error

I am trying to upload image using ajax in laravel 5.2.but still i am getting error 500 Internal Server Error in route.
when i am trying to upload image using ajax request the browser shown correct route path but still i am not getting reason why it still showing error to me.
HTML
<!-- CHANGE AVATAR TAB -->
<div class="tab-pane" id="tab_1_2">
<div class="uploadimagediv"></div>
{{ Form::open(array('url' => 'admin/avatar','method'=>'post','files'=>'true','id'=>'updateprofileimage')) }}
<div class="form-group">
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">
<img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image" alt=""/>
</div>
<div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;">
</div>
<div>
<span class="btn default btn-file">
<span class="fileinput-new">
Select image </span>
<span class="fileinput-exists">
Change </span>
<p class="text-danger" id="error_image"></p>
<input type="file" id="picture" name="picture"/>
{{--{{ Form::file('picture') }}--}}
</span>
<span class="error alert-danger">{{ $errors->first('picture') }}</span>
<a href="javascript:;" class="btn default fileinput-exists" data-dismiss="fileinput">
Remove </a>
</div>
</div>
<div class="clearfix margin-top-10">
</div>
</div>
<div class="margin-top-10">
{{Form::hidden('id', 2, ["id"=>"id"])}}
{{ Form::button('Upload',['id'=> 'updatepicture','class'=>'btn green-haze']) }}
{{--{{ Form::submit('Submit',['class' => 'btn green-haze','name'=>'changeImage']) }}--}}
<a href="javascript:;" class="btn default">
Cancel </a>
</div>
{{ Form::close() }}
</div>
<!-- END CHANGE AVATAR TAB -->
Route
Route::group(['prefix' => 'admin'], function ()
{
Route::controller('/','DashboardController');
});
Ajax
$(document).on('click', '#updatepicture', function($e)
{
$e.preventDefault();
// send an ajax request
$("#error_image").empty();
$.ajax(
{
url: 'avatar',
processData: false,
contentType: false,
type: "post",//use for update
data: new FormData($("#updateprofileimage")[0]),
success: function(data)
{
if(data.status)
{
$("#uploadimagediv").html('<div class="alert alert-success"><button type="button" class="close">×</button>'+data.message+'</div>');
window.setTimeout(function()
{
$(".alert").fadeTo(500, 0).slideUp(500, function()
{
$(this).remove();
});
}, 5000);
$('.alert .close').on("click", function(e)
{
$(this).parent().fadeTo(500, 0).slideUp(500);
});
//console.log(data);
//$("#updateprofileimage")[0].reset();
//window.location.href = "http://localhost/laravel/admin/profile";
}
else
{
errors = data.errors;
for(error in errors)
{
$("#error_"+error.title).html(error.message);
}
}
},
error: function(xhr)
{
if(xhr.status == 422)
{
errors = xhr.responseJSON;
for(error in errors)
{
$("#error_"+error).html(errors[error][0]);
}
}
}
});
});
Error is :"NetworkError: 500 Internal Server Error - http://localhost/laravel/admin/avatar"
please suggest me where i am getting wrong.
Controller is
public function postAvatar(ImageUploadRequest $request)
{
---
}
Add the below line inside <head>
<meta name="csrf-token" content="{{ csrf_token() }}">
And add the below lines before your ajax call in javascript function
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
And don't forget to give permission to your storage folder
sudo chmod -R 777 storage
In your ajax setup you have to provide x-csrf-token with the request. For your ajax request , also there is a problem with your url:
$(document).on('click', '#updatepicture', function($e)
{
$e.preventDefault();
// send an ajax request
$("#error_image").empty();
$.ajax(
{
url: "{{url('avatar')}}",
processData: false,
contentType: false,
type: "post",//use for update
data: new FormData($("#updateprofileimage")[0]),
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}"
},
success: function(data)
{
if(data.status)
{
$("#uploadimagediv").html('<div class="alert alert-success"><button type="button" class="close">×</button>'+data.message+'</div>');
window.setTimeout(function()
{
$(".alert").fadeTo(500, 0).slideUp(500, function()
{
$(this).remove();
});
}, 5000);
$('.alert .close').on("click", function(e)
{
$(this).parent().fadeTo(500, 0).slideUp(500);
});
//console.log(data);
//$("#updateprofileimage")[0].reset();
//window.location.href = "http://localhost/laravel/admin/profile";
}
else
{
errors = data.errors;
for(error in errors)
{
$("#error_"+error.title).html(error.message);
}
}
},
error: function(xhr)
{
if(xhr.status == 422)
{
errors = xhr.responseJSON;
for(error in errors)
{
$("#error_"+error).html(errors[error][0]);
}
}
}
});
});

Progress bar not working when autoProcessQueue is false

I'm using Dropzone.js to display image on my site.
It is working wonderfully, but there is one problem.
After I realized that Dropzone automatically sends image information without user pressing submit button, I set autoProcessQueue to false.
Now, it doesn't send the information automatically, but progress bar is broken as seen in the picture below.
There seems to be a white line on the image and it doesn't look good.
I had a similar problem with the progress bar. I'm using twitter-bootstrap and jQuery in my solution as well. This solution with the progress bar works fine for me (see element with id total-progress).
This is my template:
<!-- Upload preview template begin -->
<div id="preview-template" style="display: none;">
<div class="dz-preview dz-file-preview" style="display:inline-block;margin:10px;">
<div class="dz-details">
<div class="dz-filename label label-primary">
<span data-dz-name></span>
</div>
<br style="line-height:2px;" />
<div class="dz-error-message label label-danger" style="display:none;clear:both;">
<span data-dz-errormessage></span>
</div>
<br style="line-height:2px;" />
<!--<div class="dz-size" data-dz-size></div>-->
<img data-dz-thumbnail style="border-radius:5px;clear:both;" />
</div>
<!--<div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>-->
<!-- <div class="dz-success-mark"><span>?</span></div> -->
<!-- <div class="dz-error-mark"><span>?</span></div> -->
<div data-dz-remove class="btn btn-default removePicFromAlbum" title="Entfernen"><span class="glyphicon glyphicon-remove center-block" aria-hidden="true"></span></div>
<div id="total-progress" class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" style="width:100px;">
<div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress></div>
</div>
<!--<img src="removebutton.png" alt="Click me to remove the file." data-dz-remove />-->
</div>
</div>
<!-- Upload preview template end -->
And here is my Javascript code:
Dropzone.autoDiscover = false;
var {{$name or 'upload'}} = new Dropzone("div#{{$name or 'upload'}}", {
url: "{{ action("$controllerClass#store") }}"
, method: "post"
, paramName: "file" // The name that will be used to transfer the file
, maxFilesize: {{$maxFilesize or str_replace('M','',ini_get('upload_max_filesize')) }} // MB
, uploadMultiple: false
, dictDefaultMessage: "{{$text or 'Ziehen Sie Dateien in diesen Bereich, um diese hochzuladen'}}"
, previewTemplate: document.getElementById('preview-template').innerHTML
//, acceptedFiles:'image/*'
, previewsContainer: '#logoPreview'
, thumbnailWidth: {{$thumbnailWidth or 100}}
, thumbnailHeight: {{$thumbnailHeight or 100}}
, sending: function (file, xhr, formData) {
formData.append('_token', '{!!csrf_token() !!}');
}
, success: function(file, responseText) {
if(responseText != undefined) {
if (responseText.success != undefined && responseText.success == "false") {
$(file.previewElement).find('.dz-error-message').text("Fehler: " + responseText.errorMessage);
$(file.previewElement).find('.dz-error-message').css('display','inline-block');
}
else {
$(file.previewElement).find('.dz-error-message').css('display','none');
}
}
$(file.previewElement).find('#total-progress').css('display','none');
}
, error: function(file, message, xhr) {
var header = "Error " + xhr.status + ": " + xhr.statusText;
$(file.previewElement).find('.dz-error-message').text(header);
$(file.previewElement).find('.dz-error-message').css('display','inline-block');
$(file.previewElement).find('#total-progress').css('display','none');
}
, uploadProgress: function(progress) {
document.querySelector("#total-progress .progress-bar").style.width = progress + "%";
}
, completed: function(progress) {
$(file.previewElement).find('#total-progress').css('display','none');
}
, removedfile: function(file) {
removeFile(file.name);
$(file.previewElement).remove();
}
});
You binded progress bar to wrong event. Replace uploadProgress by uploadprogress.
Doc is here: http://www.dropzonejs.com/#event-uploadprogress
This post may be old but I got easy answer. So I am posting here for anyone who needs help on this.
Remove autoProcessQueue: false and set url: "#". When you set the url: "#", then dropzone can't process automatically but autoProcessQueue: true (by default) will help to trigger animation
This way, it worked for me
Dropzone.options.dropzoneForm = {
addRemoveLinks: true,
url: "#",
init: function () {
}
};

Resources