how can i enqueue a file manually in dropzone/ vue dropzone 2 - javascript

I am working on uploading functionality for a product i'm building with vuedropzone 2, from the dropzone docs http://www.dropzonejs.com/#config-autoQueue , it is possible to prevent the accepted/added files from being queued automatically by setting autoQueue to false, also it is stated there that the files can be queued manually by calling enqueueFile(file) manually.
Setting autoQueue to false works, however when i try to add the file manually to the queue, its not working and i am getting this error this.$refs.dropzone.enqueueFile is not a function
my script:
new Vue({
data: {
dropzoneOptions: {
url: 'https://httpbin.org/post',
thumbnailWidth: 150,
maxFilesize: 1000,
addRemoveLinks: true,
autoProcessQueue: false,
autoQueue: false,
dictDefaultMessage: "<i class='is-size-150 fa fa-cloud-upload'>
</i>",
headers: {
'Access-Control-Allow-Origin': '*',
},
parallelUploads: 1,
},
},
methods: {
upload() {
document.querySelector('.dropzone').click();
},
startUpload() {
this.$refs.dropzone.getAcceptedFiles().forEach(f => this.$refs.dropzone.enqueueFile(f));
....
},
})
my template:
div
button.button.is-primary(#click="upload") upload Document(s)
dropzone(
v-show="false",
:id="id",
ref="dropzone",
:maxNumberOfFiles="100" ,
:maxFileSizeInMB="1000",
:options="dropzoneOptions",
#vdropzone-upload-progress="updateFilename",
#vdropzone-files-added="handleFilesAdded",
#vdropzone-error="handleUploadError",
#vdropzone-total-upload-progress="progress",
#vdropzone-queuecomplete="handleUploadComplete",
#vdropzone-success="fileUploaded",
:parallelUploads="1",
)
// this dialog modal shows only when files have been selected after clicking upload document button
el-dialog(title="Upload Files", :visible.sync="hasAddedFiles")
div(slot="title")
// button for adding more files before clicking start upload
button.is-info.button.ml-15(#click="addFiles") Add File(s)
// table that lists all selected files
el-table(:data="addedFiles", :height="400")
el-table-column(type="index" :index="1")
el-table-column(
property="name",
show-overflow-tooltip,
label="Name",
min-width="200"
)
el-table-column(property="type" label="File type")
el-table-column(label="Delete" width="100")
template(scope="props")
// button for removing a file
button.button.trash(
:class="$style.trash",
#click="removeFile(props.row)",
)
i.material-icons delete
div(slot="footer")
// select file type
el-select(
v-model="addedFilesType"
filterable
allow-create
placeholder="Choose file(s) type"
)
el-option(
v-for="(item, index) in documentTypes"
:key="index"
:value="item"
)
// button for enqeueing and start processing the queue in order to start files upload
button.button.is-primary.is-medium.ml-15(
#click="startUpload",
:disabled="!addedFilesType.length",
)
span.icon
i.material-icons cloud_upload
span Start Upload

The enqueueFile is not delegated on the vue-dropzone component. So it's not available on this.$refs.dropzone.
But there is a solution to this (however not very elegant). You should be able to call this.$refs.dropzone.dropzone to get the underlying dropzone object.
So this.$refs.dropzone.dropzone.enqueueFile(f) should work.

Related

File Input not recognizing file upload 2nd time

I am trying to use the Krajee Bootstrap File Input to upload a file. The way it works now is I have a button, that when clicked, opens a Bootstrap modal dialog and the input file tag is inside that modal. The user clicks a browse button, selects a file, and the file gets uploaded. All of that works just fine!
My issue is if the modal is closed, then reopened again, the file input control no longer works. When I click browse, it lets me select a file, but the Krajee File Input control errors out and says:
You must select at least 1 file to upload.
Even though I select a file, it says that anyway. Like I stated before, it works fine on the first use, but after multiple uses, it starts getting that error. I imagine my issue is in the way I'm destroying and re-creating the control. Here is my modal dialog and file input control html code:
<div class="modal fade" id="modalUpload" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Upload Profile Image</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="divFileInput">
<input id="fileFileUpload" type="file" name="files"/>
</div>
<div id="divCropper">
<img id="imgCropperPicture" alt="profile" />
</div>
</div>
</div>
</div>
</div>
Here is my relevant client side code (It's written in TypeScript 2.8):
$("#fileFileUpload").fileinput({
showPreview: true,
uploadAsync: false,
uploadUrl: '/fileupload',
allowedFileExtensions: ['jpg', 'jpeg', 'png'],
allowedPreviewTypes: ['image'],
uploadExtraData: { memberId: $("#hidMemberId").val() },
resizeImage: true,
theme: 'fa',
minFileCount: 1,
maxFileCount: 1,
dropZoneEnabled: false,
showRemove: false,
showUpload: false,
showCancel: false,
overwriteInitial: true
}).on("change", () => {
$("#fileFileUpload").fileinput(("upload") as any).on("filebatchuploadsuccess", (event, data: any) => {
this.uploadFinished(data);
});
});
$('#modalUpload').on('hidden.bs.modal', (e) => {
$("#divCropper").hide();
$("#divFileInput").show();
$("#fileFileUpload").fileinput(("clearStack") as any);
$("#fileFileUpload").fileinput(("clear") as any);
$("#fileFileUpload").fileinput(("destroy") as any).fileinput({
showPreview: true,
uploadAsync: false,
uploadUrl: '/fileupload',
allowedFileExtensions: ['jpg', 'jpeg', 'png'],
allowedPreviewTypes: ['image'],
uploadExtraData: { memberId: $("#hidMemberId").val() },
resizeImage: true,
theme: 'fa',
minFileCount: 1,
maxFileCount: 1,
dropZoneEnabled: false,
showRemove: false,
showUpload: false,
showCancel: false,
overwriteInitial: true
}).on("change", () => {
$("#fileFileUpload").fileinput(("upload") as any).on("filebatchuploadsuccess", (event, data: any) => {
this.uploadFinished(data);
});
});
});
So basically, I'm initializing the file input control for the first time. The $('#modalUpload').on('hidden.bs.modal' ...) code is code that gets executed when the BootStrap modal is closed. What I'm doing is calling the destroy method on the file input control, then recreating it exactly as before.
Any help on getting this working would be appreciated!
I seemed to figure this out for myself. In case anyone else runs into this issue, the problem is because the destroy method does not remove the event handlers. So what was happening is my change event handler was getting called, but because #fileFileUpload was destroyed, it was throwing a JS error in the console window. So what I had to do was just add the line below before calling the destroy method:
$("#fileFileUpload").off("change");
I placed that line before calling the destroy method and now everything works as expected.
The first time you initialize the plugin, it will attach a listener to the -- in this case -- fileFileUpload input. When the modal is closed, it trigger the input deletion but not the listener. And so when this line is triggered :
$("#fileFileUpload").fileinput(("destroy") as any).fileinput ...
it's actually creating a new element and attach the listener, but the old listener still active and so caused your program not working as expected.
You need to remove the listener when the modal is closed.
I had the same problem even without a modal.
I now just call destroy method before I init the file input.
See commit
$("#file-data").fileinput('destroy');
$("#file-data").fileinput({
previewFileType: "any",
uploadUrl: "BLAH",
maxFileSize: BLAHBLAH
});
$("#file-data").on(
"fileuploaded",
function (event, file, previewId, index) {
DO_SOMETHING
}
);

Can't display validation errors with kartik-v bootstrap file input plugin

I've opened an issue on the github plugin, but it doesn't seem to be very active, so I asked here too.
I'm sending my files through ajax but when the upload fails (as with height too small) I don't get the real error message, but I get an error from my ajax url, but this one makes no sense since nothing is sent.
I think the ajax route shouldn't be called, but anyway, I tried to play with 'fileuploaderror' and I do get the wanted errors, but I don't know how to display them. There must be a simple way in the fileuploaderror event, but I don't know it.
Can anyone help me with this one ?
Issue link |
Plugin page
Thanks
$("#id").fileinput({
uploadUrl: "/ajax/snippet/image/send/78", // server upload action
deleteUrl: "/ajax/snippet/image/remove/",
uploadAsync: false,
showUpload: false, // hide upload button
showRemove: false, // hide remove button
maxFileCount: maxFile,
browseOnZoneClick: true,
language: "fr",
minImageWidth: 150,
minImageHeight: 150,
allowedFileExtensions: ["jpg", "jpeg", "gif", "bmp", "png"],
multiple: true,
maxFileSize: 5000,
uploadExtraData: function (previewId, index) {
return {key: index};
},
initialPreviewAsData: true,
overwriteInitial: false,
}).on("filebatchselected", function (event, files) {
// trigger upload method immediately after files are selected
$(this).fileinput("upload");
}).on('fileuploaderror', function (event, data, msg) {
var form = data.form, files = data.files, extra = data.extra,
response = data.response, reader = data.reader;
// get message
alert(msg);
});
}
Ok, I got the answer, in my "filebatchselected" event, I was forcing the upload.
I need to check if I have valid files to upload first.
$("#id").fileinput({
uploadUrl: "/ajax/snippet/image/send/78", // server upload action
deleteUrl: "/ajax/snippet/image/remove/",
uploadAsync: false,
showUpload: false, // hide upload button
showRemove: false, // hide remove button
maxFileCount: maxFile,
browseOnZoneClick: true,
language: "fr",
minImageWidth: 150,
minImageHeight: 150,
allowedFileExtensions: ["jpg", "jpeg", "gif", "bmp", "png"],
multiple: true,
maxFileSize: 5000,
uploadExtraData: function (previewId, index) {
return {key: index};
},
initialPreviewAsData: true,
overwriteInitial: false,
}).on("filebatchselected", function (event, files) {
// trigger upload method immediately after files are selected
var filesStack = $('#input-id').fileinput('getFileStack');
if (filesStack.length > 0) {
$(this).fileinput("upload");
}
});
}

correct implementation of plupdate

i´m implementing this upload library, maybe not much people use this, but maybe somebody can help me to figure how to solve this.
So i'm already uploading, the thing is that i want to implement the "uploader" objet, like
upload.bind();
i would like to know if anybody here can provide me links or maybe clear my idea.
thank you so much.
This is my code:
uploader = $("#uploader").plupload({
// General settings
runtimes: 'html5,flash,silverlight,html4',
url: objMaterial.geturl(),
urlstream_upload: true, //cambiar url en tiempo real
multi_selection: multiSelection,
unique_names: unicoNombre,
// User can upload no more then 20 files in one go (sets multiple_queues to false)
max_file_count: 1,
chunk_size: '1mb',
// Resize images on clientside if we can
filters: {
// Maximum file size
max_file_size: '50mb',
// Specify what files to browse for
mime_types: [
{
title: titulo,
extensions: extensiones
}
]
},
// Rename files by clicking on their titles
rename: true,
// Sort files
sortable: true,
// Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
dragdrop: true,
// Views to activate
views: {
list: true,
thumbs: true, // Show thumbs
active: 'thumbs'
},
// Flash settings
flash_swf_url: '../../js/Moxie.swf',
// Silverlight settings
silverlight_xap_url: '../../js/Moxie.xap'
});
//uploader = $("#uploader").plupload();
uploader = $('#uploader').plupload();
console.log(uploader);
//uploader = $("#flash_uploader").pluploadQueue();
uploader.bind('QueueChanged', function (up, files)
{
files_remaining = uploader.files.length;
});
i want to answer this question, i found a solution.
so all these objects are events.
here you have a complete example of how to implement them.
uploader = $("#uploader").plupload({
// General settings
runtimes: 'html5,html4',
url: objMaterial.geturl(),
// Maximum file size
max_file_size: '50mb',
chunk_size: '1mb',
max_file_count: 1,
// Resize images on clientside if we can
resize: {
width: 200,
height: 200,
quality: 90,
crop: true // crop to exact dimensions
},
// Specify what files to browse for
filters: [
{title: "PDF", extensions: "PDF"}
],
// Rename files by clicking on their titles
rename: true,
// Sort files
sortable: true,
// Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
dragdrop: true,
// Views to activate
views: {
list: true,
thumbs: true, // Show thumbs
active: 'thumbs'
},
// Post init events, bound after the internal events
init: {
PostInit: function () {
// Called after initialization is finished and internal event handlers bound
log('[PostInit]');
document.getElementById('uploadfiles').onclick = function () {
uploader.start();
return false;
};
},
Browse: function (up) {
                // Called when file picker is clicked                
            },
            Refresh: function (up) {
                // Called when the position or dimensions of the picker change                 
            }, 
            StateChanged: function (up) {
                // Called when the state of the queue is changed                 
            }, 
            QueueChanged: function (up) {
                // Called when queue is changed by adding or removing files                 
            },
OptionChanged: function (up, name, value, oldValue) {
// Called when one of the configuration options is changed
},
BeforeUpload: function (up, file) {
// Called right before the upload for a given file starts, can be used to cancel it if required
},
            UploadProgress: function (up, file) {
                // Called while file is being uploaded                 
            },
FileFiltered: function (up, file) {
// Called when file successfully files all the filters                 
},
            FilesAdded: function (up, files) {
                // Called when files are added to queue                
                plupload.each(files, function (file) {                     
                });
            },
            FilesRemoved: function (up, files) {
                // Called when files are removed from queue                 
                plupload.each(files, function (file) {                     
                });
            }, 
            FileUploaded: function (up, file, info) {
                // Called when file has finished uploading
jQueryMessage('El archivo se ha enviado exitosamente!', 1);                 
            }, 
            ChunkUploaded: function (up, file, info) {
                // Called when file chunk has finished uploading                 
            },
UploadComplete: function (up, files) {
// Called when all files are either uploaded or failed                 
},
Destroy: function (up) {
// Called when uploader is destroyed                 
},
            Error: function (up, args) {
                // Called when error occurs                 
            }
    },
// Flash settings
flash_swf_url: '/plupload/js/Moxie.swf',
// Silverlight settings
silverlight_xap_url: '/plupload/js/Moxie.xap'
});
i hope this can help you

fine upload validation set

I´m using the Fine Upload-Plugin.
I want to upload .docx-files to my application ... only .docx-files.
Surely this is easy to handle with a query, like
if (extension == "docx")
upload something
But I saw a field in which you can specify a data type like "All types" or "All images".
Where can i add/manipulate this validation?
I tried the acceptFiles-options, but this only prevent uploads.
I want to give the user the possibility to show .docx-files only.
HTML-Code:
<div id="manual-fine-uploader"></div>
<div id="triggerUpload" class="btn btn-primary" style="margin-top: 10px;display:none">
<i class="icon-upload icon-white"></i> Datei einfügen
</div>
<div id="uploadNewFile"></div>
JS-Code
$("#uploadNewFile").fineUploader({
element: document.getElementById('manual-fine-uploader'),
request: {
endpoint: 'Upload.aspx'
},
autoUpload: true,
//Part, that may be important
///MEME-Type: docx
acceptFiles: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
allowedExtensions: ["docx"],
//Endpart
maxConnections: 1,
multiple: false,
chunking: {
enabled: true
},
resume: {
enabled: true
},
text: {
uploadButton: 'Datei hochladen'
}
});
EDIT:
Maybe the Question isnt clear enough:
I need a specific filter within the select-file-dialog.
Like the standard "images only" or "all types" etc..
How to add these kind of filter?
Here you see the select
Your allowedExtensions and acceptFiles options are not in the correct place. Your code should look like this:
$("#uploadNewFile").fineUploader({
element: document.getElementById('manual-fine-uploader'),
request: {
endpoint: 'Upload.aspx'
},
validation: {
acceptFiles: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
allowedExtensions: ["docx"]
},
maxConnections: 1,
multiple: false,
chunking: {
enabled: true
},
resume: {
enabled: true
},
text: {
uploadButton: 'Datei hochladen'
}
});
Please see the validation option in the documentation for more details, along with the validation feature page.
Also, if you are using Fine Uploader 4.x, the text.uploadButton option was removed as part of the templating redesign. In 4.x and newer, you can specify the button name, among other things, in a template you declare in your markup.
Finally, I removed the autoUpload option from your configuration, as you were setting it to the default value. No need to declare it in that case.

scriptData not being passed when there are multiple instances of uploadify

I've got two instances of uploadify in my form. You'll find the definitions below.
And two buttons that trigger the uploads. The image button is the only one relevant to the question:
$( "#btnimageupload" ).button().click(function()
{
$('#picbrowse').uploadifySettings( 'scriptData', ({ 'isSelected': $( '#selectImage' ).val() }));
$('#picbrowse').uploadifyUpload();
});
Now, here's the issue:
When I click btnimageupload button, the image doesn't upload. The progressbar goes to 100 and stops. No errors, javascript or otherwise.
But, when I disable the vdobrowse file input box, and its corresponding script, everything works fine. The images are uploaded and the data is transferring.
Here's the tricky part... if I don't pass the scriptData on the btnimageupload click handler, images will upload even with vdobrowse file input box on the page.
So it seems to me like scriptData is breaking uploadify when there's more than one instance of uploadify on the page.
Anyone know how I could solve this?
Uploadify definitions
$('#picbrowse').uploadify(
{
uploader : 'script/uplodify/uploadify.swf',
script : '../../dopost.php',
cancelImg : 'script/uplodify/cancel.png',
folder : '/images',
queueID : 'picqueue',
auto : false,
multi : true,
fileDesc : 'Image Files',
fileExt : '*.gif;*.jpg;',
queueSizeLimit: 5,
scriptData:
({
'action': 'upload_image',
}),
onComplete: function( event, queueID, fileObj, response, data )
{
console.log( reponse)
}
});
.
$('#vdobrowse').uploadify(
{
uploader : 'script/uplodify/uploadify.swf',
script : '../../dopost.php',
cancelImg : 'script/uplodify/cancel.png',
folder : '/video',
queueID : 'vdoqueue',
auto : false,
multi : true,
fileDesc : 'Video Files',
fileExt : '*.avi;*.mpg;*.mov;*.mp4;*.mpeg;*.flv;*.mkv;*.wmv',
queueSizeLimit: 5,
scriptData:
{
action: 'upload_video'
},
onComplete: function( event, queueID, fileObj, response, data )
{
console.log( response );
}
});
The plugin appears to be putting the
options into global space, which is
why when you are using two or more
uploadify's with scriptData it is
picking up the last stored value in
scriptData.
I see running two uploadify's on one
page a pointless exercise and as such
I never test the functionality with
multiple uploadify's.
uploadifySettings works perfectly with
one uploadify. Multiple uploadify's
are the demo page to demonstrate the
different setups possible.
That said, it is still obviously a
problem for users and we will need to
fix it for those that wish to use
multiple uploadify's on the same page.
Forum
I suggest to use swfUpload. I am use in at my project and tested with multiple instances and it's work perfect. So swfUpload easy to understand and api looks like as uploadify api.
Given that there seems to be a limitation with scriptData and multiple Uploadifys on a page, what you could do is skip the scriptData and folder attributes and parse out the file types inside dopost.php and take an action based on that.
For example:
$fileParts = pathinfo($_FILES['Filedata']['name']);
$extension = strtolower($fileParts['extension']);
switch($extension){
case "gif" | "jpg":
// Do Image Upload Action
break;
case "avi" | "mpg" | "mov" | "mp4" | "mpeg" | "flv" | "mkv" | "wmv":
// Do Video Upload Action
break;
}
I'm receiving the scripData just fine, I've made an example on my website
I've limited the upload size to 500KB for obvious reasons and corrected the code:
$('#picbrowse').uploadify(
{
uploader : 'uploadify.swf',
script : 'uploadify.php',
cancelImg : 'cancel.png',
folder : 'uploads/images',
queueID : 'picqueue',
auto : false,
multi : true,
removeCompleted : false,
fileDesc : 'Image Files',
fileExt : '*.gif;*.jpg',
sizeLimit : 512000,
queueSizeLimit: 5,
scriptData: {action: 'upload_image'},
onComplete: function( event, queueID, fileObj, response, data )
{
$ul.html('');
var json = jQuery.parseJSON(response);
$.each(json,function(k,v){
var li = "<li>"+k+": "+v+"</li>";
$ul.append(li);
});
},
onError: function (event,ID,fileObj,errorObj) {
console.log(errorObj.type + ' Error: ' + errorObj.info);
}
});
$('#vdobrowse').uploadify(
{
uploader : 'uploadify.swf',
script : 'uploadify.php',
cancelImg : 'cancel.png',
folder : 'uploads/video',
queueID : 'vdoqueue',
auto : false,
multi : true,
sizeLimit : 512000,
fileDesc : 'Video Files',
fileExt : '*.avi;*.mpg;*.mov;*.mp4;*.mpeg;*.flv;*.mkv;*.wmv',
queueSizeLimit: 5,
scriptData: {action: 'upload_video'},
onComplete: function( event, queueID, fileObj, response, data )
{
$ul.html('');
var json = jQuery.parseJSON(response);
$.each(json,function(k,v){
var li = "<li>"+k+": "+v+"</li>";
$ul.append(li);
});
}
});
And I'm using the standard uploadify.php and echoing the POST variable instead:
echo json_encode($_POST);

Categories

Resources