Dropzone.js acceptedFiles not working with drag&drop - dropzone.js

I have set Dropzone to accept only this files:
acceptedFiles:
"application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/msword",
also tried in this other two ways:
acceptedFiles: ".docx, .doc",
acceptedFiles:
"application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/msword, .docx, .doc",
but isn't working with drag&drop. It's working only with the "clickable" option, so the fileInput is doing his job.
The function getAcceptedFiles() returns an empty array []. It is only the visual impact that shows the dropped files. Am I missing something? I have to manually exclude them from the preview?
Thanks for you help.

Seems that there isn't a default implementation for this. You must implement the logic for the drag&drop.
const maxFilesNumber = 1;
//after complete adding files, remove if not accepted or maxFilesNumber reached
dropzone.on("complete", (file) => {
if (!file.accepted || dropzone.files.length > maxFilesNumber)
dropzone.removeFile(file);
});
dropzone.on("maxfilesreached", () => dropzone.disable() );
//reset event is fired when files in dropzone are 0
dropzone.on("reset", () => dropzone.enable() );

Related

How to set up Dropzone.js to upload multiple and upload in chunks at the same time?

I'm trying to set up Dropzone.js to handle multiple files at the same time, but also upload each one in 1mb chunks. I can't seem to find the right DZ configuration for this.
When I add "uploadMultiple: true" to my working chunking implementation of DZ, Chrome throws this error: "Uncaught Error: You cannot set both: uploadMultiple and chunking."
The Problem: "autoProcessQueue" was set to "false" because I only wanted to process when the user hits a "submit" button. Even with "uploadMultiple" not set to true, Dropzone will upload more than one file (presumably consecutively rather than simultaneously) as long as the queue is auto-processed.
The Solution:
Dropzone.js calls "chunksUploaded" once all the chunks for a file are uploaded. After the first file successfully uploads all of its chunks, reset the "autoProcessQueue" option to "true." After "queueComplete," set it back to "false" in preparation for the next upload.
See the answer here to understand the chunksUploaded callback, in the context of using it to concatenate chunks following upload: How to concatenate chunked file uploads from Dropzone.js with PHP?
See the end of this thread for turning on/off autoProcessQueue: https://github.com/enyo/dropzone/issues/462
Javascript sample snippet:
( I stripped out all Dropzone and Ajax options to highlight the relevant parts )
var myDropzone = new Dropzone(target, {
chunksUploaded: function(file, done) {
// ajax below posts to a script that merges the uploaded chunks of the current file
$.ajax({
success: function (data) {
myDropzone.options.autoProcessQueue = true;
done();
}
});
}
});
myDropzone.on("queuecomplete", function() {
myDropzone.options.autoProcessQueue = false;
});

React-Admin | Cannot upload a file using FileInput

First time with React-Admin. I am using it to create a panel that basically monitors some parameters that I get from an API. However, one section requires a .csv file to be uploaded. I am trying to implement it with FileInput but I am unable to catch the file. I don't understand how to do it.
File selection step (from pc to browser) is working properly, but my problem is that I cannot handle the file after that step. I read the docs, but I don't know how to do it. I tried many different ways but I am getting crazy.
Below is the basic code. I guess I have to add a handler or something similar but, how? I have little experience with React too. I know the basics, but I just built a couple of (super) simple apps. Just for learn.
// UploadFile.js
...
export const UploadSection = props => (
<SimpleForm>
<FileInput source="csvFile" label="Upload file (.csv)" accept="text/csv" >
<FileField source="src" title="title" />
</FileInput>
</SimpleForm>
);
// App.js
...
const App = () => (
<Admin dataProvider={dataProvider} authProvider={authProvider} >
...
<Resource name="uploadSection" list={UploadSection} />
...
</Admin>
);
The question:
How can I catch the .csv file?
Thanks in advance!
After working on it during hours I got it working.
First problem (the one I commented #selens answer): I got Uncaught TypeError: _this.props.save is not a function because I wasn't working in Create or Edit View. It seems you need to use FileInput in Create or Edit Views. If not, Save button won't work.
From docs:
save: The function invoked when the form is submitted. This is passed automatically by react-admin when the form component is used inside Create and Edit components.
Second problem: In my case I upload one file at a time (multiple={false} in FileInput). However, the code addUploadFeature.js is ready to use with multiple files. So, I edited part of addUploadFeature.js to upload just one file. See the complete file below.
// addUploadFeature.js
const convertFileToBase64 = file => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file.rawFile);
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
});
const addUploadFeature = requestHandler => (type, resource, params) => {
if (type === 'UPDATE' && resource === 'myResource') {
if (params.data.myFile) {
// NEW CODE HERE (to upload just one file):
const myFile = params.data.myFile;
if ( !myFile.rawFile instanceof File ){
return Promise.reject('Error: Not a file...'); // Didn't test this...
}
return Promise.resolve( convertFileToBase64(myFile) )
.then( (picture64) => ({
src: picture64,
title: `${myFile.title}`
}))
.then( transformedMyFile => requestHandler(type, resource, {
...params,
data: {
...params.data,
myFile: transformedMyFile
}
}));
}
}
return requestHandler(type, resource, params);
};
export default addUploadFeature;
After all, I was able to send the file to the server in Base64 format.
Hope this to be useful for somebody in the future ;)
I have a similar problem, I cannot upload a file and issue will be in accept prop.
You can use the following code:
<FileInput source="csvFile" label="Upload file (.csv)" accept=".csv" >
Instead of:
<FileInput source="csvFile" label="Upload file (.csv)" accept="text/csv" >
Have you checked the DataProvider and UploadFeature sections in the documentation?
If you have your own DataProvider, you can create a new file addUploadFeature.js and customize it as in the sample under this link:
https://marmelab.com/react-admin/DataProviders.html#extending-a-data-provider-example-of-file-upload

Remove previews from dropzone after success

I want to rollback the original dropzone with its message "drop files here" after the success event of dropzone or after the complete event of dropzone.
I don't want to see the preview after success or complete.
This is my dropzone script:
Dropzone.options.myAwesomeDropzone = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 2, // MB
parallelUploads: 1,
success: function(file, response) {
var imageSrc = response;
$(".img-responsive").attr('src', imageSrc);
if (imageSrc == '/assets/images/offerfeatimg.jpg') {
$(".removebutton").hide();
} else {
$(".removebutton").show();
}
}
};
Leveraging #kkthxby3 's idea, the innerHTML for the thumbnail can be cleared in the success method using the following code:
success: function (file, response) {
file.previewElement.innerHTML = "";
}
The beauty of this approach is that it clears the thumbnail without firing the removedFile event.
This leaves the following html in the dom where the thumbnail was:
<div class="dz-preview dz-processing dz-image-preview dz-complete"></div>
but as you can see, the div above which is responsible for displaying the thumbnail is now empty.
Another approach is to remove even the enclosing div that wraps the thumbnail along with it's contents. This approach can be accomplished with the following code in the success method and leaves no trace of the thumbnail in the dom:
success: function (file, response) {
file.previewElement.parentNode.removeChild(file.previewElement);
}
Enjoy.
only need call method removeFile in success function
success: function (file, response) {
this.removeFile(file);
}
check doc dropzone
For me the easiest way to make the file preview not appear is with css.
dz-preview and dz-file-preview are a couple classes in the outer div of the preview html generated by the default template.
.dz-preview, .dz-file-preview {
display: none;
}
I also told it to not create thumbnails in the Dropzone.options.
Dropzone.options.myDropzone = {
paramName: "file",
maxFilesize: 2, // MB
url: 'post_image',
createImageThumbnails: false, // NO THUMBS!
init: function () {
this.on('sending', dz_sending),
this.on('success', dz_success),
this.on('error', dz_error),
this.on('complete', dz_complete) // Once it's done...
}
The template still generates all the preview html though. So in my 'complete' function dz_complete I delete it all.
function dz_complete(file) {
$('.dz-preview').remove(); // ...delete the template gen'd html.
}
Just an fyi...
The method 'removeAllFiles' is not necessarily the prime choice. Which is the same as 'removeFile(file)'.
I have an event handler for dropZone's 'removedfile' event... I'm using it to send a server message to delete the respective file from the server (should a user delete the thumbnail after it's been uploaded). Using the method 'removeAllFiles' (as well as the individualized 'removeFile(file)') fires the event 'removedfile' which deletes the uploaded images in addition to clearing the thumbnails.
So one could add some finessing around this but in the reality of it the method is not correct.
Looking through the api for Dropzone I am not seeing an API call to simply reset or clear the thumbnails... The method 'disable()' will clear the stored file names and what not but does not clear the thumbnails... Seems dropzoneJS is actually missing a critical API call to be honest.
My work around is to manually reset the containing div for dropzone:
document.getElementById("divNameWhereDropzoneClassIs").innerHTML = ""
This clears the thumbnails without firing off the event 'removedfile' which is supposed to be used for deleting an image from the server...
The easiest thing is to call the dropzone removeFile() method, using an event listener for the success event.
Dropzone.options.myAwesomeDropzone = {
paramName: "file",
maxFilesize: 2,
parallelUploads: 1,
init: function() {
this.on("success", function(file, response) {
var imageSrc = response;
$(".img-responsive").attr('src', imageSrc);
if(imageSrc == '/assets/images/offerfeatimg.jpg') {
$(".removebutton").hide();
} else {
$(".removebutton").show();
}
this.removeFile(file); // This line removes the preview
})
}
};
I was using file.previewElement.remove(), works fine in Chrome but does not work in IE.
Then I tried this.removeFile(file), but it didn't work for me.
After that i tried file.previewElement.innerHTML = "" which works in both Chrome and IE but it leaves an extra div where the preview elements were.
So this one works better for me...
success: function (file, response) {
file.previewElement.outerHTML = "";
}
If you want to remove an added file from the dropzone, you can call .removeFile(file). This method also triggers the removedfile event.
Here’s an example that would automatically remove a file when it’s finished uploading:
myDropzone.on("complete", function(file) {
myDropzone.removeFile(file);
});
If you want to remove all files, simply use .removeAllFiles(). Files that are in the process of being uploaded won’t be removed. If you want files that are currently uploading to be canceled, call .removeAllFiles(true) which will cancel the uploads.
100% Tested and Working:
$('#preview_image_container .dz-preview .dz-remove').attr('id','removeFile');
document.getElementById("removeFile").click();

Settings, formdata or uploader value, swfuploadify is undefined

I'm experimenting with allowing the user to change upload folders, so I'm trying to use
onUploadStart and the settings to change some values after document.ready and intializing uploadify. But I keep getting this error in the settings function of uploadify
swfuploadify.settings is undefined. using IE11 and the F12 debug
So I suspect that it means that the swf flsh object has not initialized yet, because I can see the values that I set using the debug.
Or am I just missing the boat here on this one?
$('[id*="_fu_Preview_Container_Upload_Images"]').uploadify({
'swf': 'uploadify.swf',
'uploader': 'fileUploader.ashx?type=images&fP=' + escape(folderPath),
'buttonClass': 'uploadify-button',
'buttonText': 'SELECT IMAGE',
'fileSizeLimit': 0,
'fileTypeDesc': 'Pictures',
'fileTypeExts': '*.jpg; *.gif; *.png;',
'onUploadStart': function (file) {
var uploadifyPath = $('[id*="_ddl_PC_UploadP_SelectFolder_Field"] option:selected').val();
$('[id*="_fu_Preview_Container_Upload_Images"]').uploadify('settings', 'uploader', escape(uploadifyPath), true);
$('[id*="_fu_Preview_Container_Upload_Images"]').uploadify('settings', 'formdata', {
'uploadPath': escape(uploadifyPath)
}, true);
},
'onSWFReady': function () {
},
'onUploadSuccess': function (file, data, response) {
Well after a little thought last night, I decided to remove the event onUploadStart and the uploadify settings.
I wrapped the upload element in an update panel, and set the folder selection to autopostback, knowing that the jquery script would just reload the uploadify button.
So now it works, I can change upload folder destinations.
But what I should really do is take out the update panel, and adjust the scripts.

Uploadify - how to abort uploading?

I have simple problem with Uploadify. Before upload starts, I want to check some criteria, it true - I want to abort uploading. The code below doesn't works properly, it uploads file even if I call the uploadifyCancel. How to fix it ?
$("#fileuploader").uploadify({
uploader: '/Scripts/uploadify.swf',
script: '/Upload/'
fileDataName: 'file',
buttonText:'upload',
multi: false,
sizeLimit: 369878,
simUploadLimit: 1,
cancelImg: '/Images/uploadify-cancel.png',
auto: true,
onOpen:function(event,ID,fileObj) {
var found = $('#uploaded-files-table tr[some-attr="1"]');
if($(found).length == 0){
$('#list').attr('disabled','disabled');
} else {
$("#fileuploader").uploadifyClearQueue();
$("#fileuploader").uploadifyCancel(ID);
}
}
});
I am not sure which version your using But I could do it below way.
I need stop file upload based on file extension
'onAddQueueItem':function(file, e) {
if (!(/\.(gif|jpeg|png|pdf)$/i).test(file.name)) {
$($this).data("uploadifive").removeQueueItem(file, 0, 10);
file.skip = true; //This skip property stop uploading file
}
}
The $("#fileuploader").uploadifyCancel(ID); code is working properly. If you add in an onComplete and an onAllComplete, neither one of these events gets hit signifying that cancel event worked.
The problem is that uploadify inherently starts uploading the file BEFORE the onOpen event occurs. Check here, it looks like they were having the same issues with modifying script data on onOpen http://www.uploadify.com/forums/discussion/5611/uploadifysettings-not-posting-new-script-data/p1
I did have some success canceling files if they were over 600-700KB in size with both $("#fileuploader").uploadifyCancel(ID); and $("#fileuploader").uploadifyClearQueue();. I think this has to deal with the speed of the upload. Because these were larger files, the cancel event had time to fire before the upload finished. On a live server, not on your local host, the upload times would be slower so MAYBE there wouldn't be a problem with the events canceling in time. I wouldn't risk it though.
A possible workaround is to include a secondary button on the page that starts the upload and remove the auto: 'true' from your uploadify init. This way, you could check whatever values you need to before the upload begins.
use onSelect of uploadify to check.
You can do like this:
$("#fileuploader").uploadify({
uploader: '/Scripts/uploadify.swf',
script: '/Upload/'
fileDataName: 'file',
buttonText:'upload',
multi: false,
sizeLimit: 369878,
simUploadLimit: 1,
cancelImg: '/Images/uploadify-cancel.png',
auto: true,
'onSelect': function (file) {
if(file.type==".zip")
{//do something
}
else
{
//cancel upload
}

Resources