Uploadify - how to abort uploading? - uploadify

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
}

Related

Is there a way to "force" a visit?

I'm using the cy.visit() command but the website i'm visiting (which i don't own) doesn't always fire the load event, although the content itself that i need for testing does appear on the website.
Despite the content appearing, since the load event is not fired sometimes (for some reason which i can't fix since i don't have ownership over this website), the cy.visit() command fails.
Is there a way to "force" it somehow, similar to how we can pass { force: true} for the cy.click() command?
Add the below to your cypress commands file
Cypress.Commands.add('forceVisit', url => {
cy.window().then(win => {
return win.open(url, '_self');
});
});
And in your tests, you can call
cy.forceVisit("www.google.com")
It's hard to simulate the problem, but I think I managed by setting pageLoadTimeout really low (30ms).
You can catch the onLoad fail in an event handler and checking for the page load error message.
I recommend doing it in a beforeEach().
beforeEach(() => {
Cypress.config("pageLoadTimeout", 30) // set this to whatever time length
// you feel is appropriate to start testing
// You'll need to experiment to get this right
// and in CI it will be a lot longer
cy.once('fail', (err) => { // "once" to just catch a single error
const message = err.parsedStack[0].message
if (message.match(/Timed out after waiting `\d+ms` for your remote page to load/)) {
return false
}
throw err // any other error, fail it
})
cy.visit('www.example.com');
})
it('checks the heading of the page', () => {
cy.get('h1').should('have.text', 'Example Domain') // ✅
})
As you can already assume, that is highly discouraged. It also really depends on how it fails and with which errors, but, without any code to reproduce, you may want to try this if you haven't already:
cy.visit('/', {failOnStatusCode: false});
Reference: https://docs.cypress.io/api/commands/visit#Arguments

Dropzone.js acceptedFiles not working with drag&drop

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() );

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;
});

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.

Resources