Dropzone Js max File upload not work properly - javascript

Notes : i tired all questions & answer related this topic.
I use Dropzone js in my application. i want to restrict only 3 file Upload in my dropzone then work fine.
issue is i upload four Number file then my all previous three file remove. that is not correctly .
i want to only alert in upload (four number file). but previous first three File not remove .
Steps:
1. First three file Upload in dropzon.
2. Add one more File in Dropzone. Then alert mess. only and not Previous File Remove
My Code Here

https://jsfiddle.net/mxxa0bk8/16/
var accept = ".png";
Dropzone.autoDiscover = false;
// Dropzone class:
var myDropzone = new Dropzone("#mydropzone", {
url: "/file/post",
acceptedFiles: accept,
uploadMultiple: false,
createImageThumbnails: false,
addRemoveLinks: true,
maxFiles: 3,
maxfilesexceeded: function(file) {
alert("No moar files please!");
},init: function() {
this.on("maxfilesexceeded", function(file) {
this.removeFile(file);
});
this.on('error', function(file, errorMessage) {
var mypreview = document.getElementsByClassName('dz-error');
mypreview = mypreview[mypreview.length - 1];
mypreview.classList.toggle('dz-error');
mypreview.classList.toggle('dz-success');
});
}
});

The following code snippet will make your dropzone remove files when they are completed:
this.on("complete", function(file) {
this.removeFile(file);
});
Add this right under:
this.on('error', function(file, errorMessage) {
var mypreview = document.getElementsByClassName('dz-error');
mypreview = mypreview[mypreview.length - 1];
mypreview.classList.toggle('dz-error');
mypreview.classList.toggle('dz-success');
});

Related

When uploading files to dropzone from mobile, ONLY ONE file gets processed

I recently opened an issue on the Dropzone repo, but here is a summary of what happens.
If I go on the app on mobile to upload images and select Take a Photo or Video, only the last photo captured will be submitted to the server. If I take 3 photos, only the array submitted will only contain the LAST photo. The weird thing is, if I upload 3 photos from the library, it works perfectly.
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("div#mydropzone",{
url: "<%= request.base_url %>/uploadfiles",
autoProcessQueue: false,
uploadMultiple: true,
addRemoveLinks:true,
parallelUploads:10,
init: function () {
$('#myForm').submit(function(e){
if (isFormValid()){
if(myDropzone.getQueuedFiles().length > 0){
e.preventDefault();
console.log(myDropzone.files)
document.getElementById('modal-main-text').innerText = myDropzone.files.length
myDropzone.processQueue();
}
}
else {
return false;
}
});
},
....other code...
One thing I know, is that before it hits the server... the console.log(myDropzone.files) dropzone does have the correct number of files.

Dropzone upload size limit to 256MB even set to 2000MB

Got this weir problem try to solve it with no luck for days. Hope anyone here can help.
The code working fine at the local machine but production on ruby, the upload file size limited to 256MB, the upload window closes itself with no error messages
<% content_for :javascript do %>
<%= javascript_include_tag 'audio_files.js' %>
<script>
$(function() {
Dropzone.autoDiscover = false;
var mediaDropzone= new Dropzone("#media-dropzone",
{maxFilesize: 2000,
paramName: "audio_file[file]",
maxFiles:1,
timeout:0 ,
init: function() {
this.on("maxfilesexceeded", function(file){
alert("No more files please!");
});
},
complete: function (file) {
if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
//once all the files have been uploaded - close window and refresh page.
//close modal and refresh page.
//alert("MADE IT HERE");
$('#download').modal('hide');
location.reload();
}
}
});// max file size is 256MB // set param of uploaded file.)
/* $("#media-dropzone").dropzone({
paramName: "audio_file[file]"
});*/
//return mediaDropzone.on("success", function(file, responseText) {
//var imageUrl;
//imageUrl = responseText.file_name.url;
// });
Dropzone.options.mediaDropzone= {
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
}
});

Direct Upload of Image to S3 after Manual Cropping with Cropper.js

This is my first post, so be gentle! I'm a Rails beginner and clueless with JavaScript/JQuery...
I have a Rails project which requires that the user be able to select a file and be presented with a preview image, which they can then crop as they wish before uploading the cropped image asynchronously.
I have successfully implemented direct upload to S3 using the JQuery FileUpload plugin (following this tutorial) and I am able to present the user with a preview image which they can crop using Cropper.js. However I need help with the last step of uploading the cropped image.
Here is the JS I have so far for handling the image crop/upload to S3:
$(document).ready(function() {
$('.directUpload').find("input:file").each(function(i, elem) {
var fileInput = $(elem);
var form = $(fileInput.parents('form:first'));
var submitButton = form.find('input[type="submit"]');
var progressBar = $("<div class='bar'></div>");
var barContainer = $("<div class='progress'></div>").append(progressBar);
fileInput.after(barContainer);
fileInput.fileupload({
fileInput: fileInput,
url: form.data('url'), //read AWS config via form attributes
type: 'POST',
autoUpload: false, // prevent upload start on file selection
formData: form.data('form-data'),
paramName: 'file',
dataType: 'XML',
replaceFileInput: false,
The code above initializes JQuery FileUpload and passes my S3 configuration data.
Next I use the JQuery FileUpload's 'add' callback to display a preview image/cropbox, and to upload the image to S3 when the user clicks an 'Upload' button:
add: function (e, data) {
if (data.files && data.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#preview_image').attr('src', e.target.result); // insert preview image
$('#preview_image').cropper() // initialize cropper on preview image
};
reader.readAsDataURL(data.files[0]);
};
$('#upload_image').on('click', function(){
$('#preview_image').cropper('getCroppedCanvas').toBlob(function (blob){
var croppedFile = new File([blob], 'cropped_file.png')
// How do I now get my cropped file data to upload instead of original file?
})
data.submit();
});
},
It is the last part, above, where I am now stuck - I've created a file from the cropped area, but have been unable to find a way to upload it instead of the original image.
The remaining code deals mainly with displaying upload progress and building an image URL that I can save to my database for image retrieval.
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
progressBar.css('width', progress + '%')
},
start: function (e) {
submitButton.prop('disabled', true); //disable submit button while image is loading
progressBar.
css('background', 'green').
css('display', 'block').
css('width', '0%').
text("Loading...");
},
done: function(e, data) {
submitButton.prop('disabled', false);
progressBar.text("Uploading done");
// extract key from S3 XML response and generate URL for image
var key = $(data.jqXHR.responseXML).find("Key").text();
var url = '//' + form.data('host') + '/' + key;
// create hidden field containing image URL, which can then be stored in model
var input = $("<input />", { type:'hidden', name: 'image_url[]', value: url })
form.append(input);
},
fail: function(e, data) {
submitButton.prop('disabled', false);
progressBar.
css("background", "red").
text("Failed");
}
});
This worked for me
var croppedFile = new File([blob], 'cropped_file.png');
data.files[0] = croppedFile;
data.originalFiles[0] = data.files[0];
or just
data.files[0] = new File([blob], 'cropped_file.png');
data.originalFiles[0] = data.files[0];
and then
data.submit()

Rename uploaded file so it can be removed DropZone.js

I have decided to update this question as I still can't change the imageId
This is my current dropzone implementation
$("div#UploadImage").dropzone({
url: '#Url.Action("SaveUploadedPhoto", "Listing", new { advertId = #Model.AdvertId })',
addRemoveLinks: true,
init: function () {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
$("input[type=submit]").on("click", function (e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
myDropzone.on("success", function (file, rep) {
console.log(rep.UniqueId);
fileList[i] = { "serverFileName": rep.UniqueId, "fileName": rep.UniqueId, "fileId": rep.UniqueId, "name": rep.UniqueId };
i++;
console.log(fileList);
});
myDropzone.on("removedfile", function (file) {
var rmvFile = "";
for (f = 0; f < fileList.length; f++) {
if (fileList[f].fileName == file.name) {
rmvFile = fileList[f].serverFileName;
}
}
if (rmvFile) {
$.ajax({
url: '#Url.Action("DeleteUploadedFile", "Listing")',
type: "POST",
data: { "id": rmvFile }
});
}
});
},
maxFilesize: 2,
maxFiles: 12
});
When I upload an image, we pass the image to a third party company which returns a uniqueId for that image, this uniqueId then gets saved in my database, I then pass this uniqueId back to the view which will become the uploaded image name, I'm trying to do this in the "success" function in the above implementation of dropzone, when I do
console.log(rep.UniqueId);
I can see the value and its correct.
When I press "Remove image" on dropzone the "removedFile" function is called, this doesn't fire to the controller because rmvFile is the old image name and it doesn't find a match within the for loop, I know this because when I do
console.log(rmvFile);
It shows the old name, now my question is what am I doing wrong here? how can I change the uploaded image name or id to the uniqueId which is returned after the uploaded has been completed? so I can successfully delete it as and when it required.
I have browsed the web, tried situation's which has resulted in how my success method currently looks.
I've managed to get this working now, after trying many different solutions.
I have found doing the following passes in the uniqueId for the image
file.serverId['UniqueId'],

Jquery File Upload always fails with File Upload Aborted

I'm trying to get Blueimp's Jquery File Upload plugin working on my website, but for the life of me can't get it to upload files. I've been working on this all day and am stuck. It will upload the file and submit it to the UploadHandler class, but when it's trying to complete the handle_file_upload function it gets to:
file_put_contents(
$file_path,
fopen('php://input', 'r'),
$append_file ? FILE_APPEND : 0
);
but that always returns 0. I cannot figure out why the file won't upload. The full response I get back is:
{"files":[
{"name":"1397489968-32",
"size":0,
"type":"multipart\/form-data; boundary=----WebKitFormBoundaryrmi4L2ouOmB4UTVm",
"error":"File upload aborted",
"deleteUrl":"http:\/\/onceridden.demomycms.co.uk\/eshop\/library\/ajax\/?file=1397489968-32",
"deleteType":"DELETE"}
]}
ajax.file-upload.php only instantiates UploadHandler, nothing else.
If you'd like to see the full code you for UploadHandler you can download it from github, it's too big for me to post on here.
Can someone please tell me why the files won't upload? Yes I've done the basics such as checking the folder is CHMOD 777. I've tried this with various files of different types (they must be images to work, limited to jpg, png or gif) and sizes; all produce the same result.
As requested this is the JS file:
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = '/eshop/library/ajax/ajax.file-upload.php',
uploadButton = $('<button/>')
.addClass('btn btn-primary')
.prop('disabled', true)
.text('Processing...')
.on('click', function () {
var $this = $(this),
data = $this.data();
$this
.off('click')
.text('Abort')
.on('click', function () {
$this.remove();
data.abort();
});
data.submit().always(function () {
$this.remove();
});
});
$('#register-photo').fileupload({
url: url,
dataType: 'json',
autoUpload: false,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
maxFileSize: 5000000, // 5 MB
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
previewMaxWidth: 100,
previewMaxHeight: 100,
previewCrop: true
}).on('fileuploadadd', function (e, data) {
data.context = $('<div/>').appendTo('#register-files');
$.each(data.files, function (index, file) {
var node = $('<p/>')
.append($('<span/>').text(file.name));
if (!index) {
node
.append('<br>')
.append(uploadButton.clone(true).data(data));
}
node.appendTo(data.context);
});
}).on('fileuploadprocessalways', function (e, data) {
var index = data.index,
file = data.files[index],
node = $(data.context.children()[index]);
if (file.preview) {
node
.prepend('<br>')
.prepend(file.preview);
}
if (file.error) {
node
.append('<br>')
.append($('<span class="text-danger"/>').text(file.error));
}
if (index + 1 === data.files.length) {
data.context.find('button')
.text('Upload')
.prop('disabled', !!data.files.error);
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#register-progress .progress-bar').css(
'width',
progress + '%'
);
}).on('fileuploaddone', function (e, data) {
$.each(data.result.files, function (index, file) {
if (file.url) {
var link = $('<a>')
.attr('target', '_blank')
.prop('href', file.url);
$(data.context.children()[index])
.wrap(link);
} else if (file.error) {
var error = $('<span class="text-danger"/>').text(file.error);
$(data.context.children()[index])
.append('<br>')
.append(error);
}
});
}).on('fileuploadfail', function (e, data) {
$.each(data.files, function (index, file) {
var error = $('<span class="text-danger"/>').text('File upload failed.');
$(data.context.children()[index])
.append('<br>')
.append(error);
});
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
It's pretty much the default file you get with the plugin with just the ID's changed to match my form.
Update
After much playing around and testing I have found out that the problem occurs when you change the name of the input from files to anything else. Why I have no idea. This is obviously an issue if you want to have it running on more than one input on a page...
I created a very simple version of the interface myself, and that does allow me to change the file name, so it must be something to do with the example they use. I would like to be able to use preview images and the such (something I couldn't figure out in my simple test) so I need to solve this issue.
This is in case anyone else ever gets stuck on this problem as well. The issue is caused by the paramName option, which if not set takes it's value from the input name. It's not set by default, so when changing the input name I was also changing paramName, meaning it no longer matched the variable coming back from the UploadHandler class.
The solution is to add paramName: 'files[]' as an option.
I was facing same issue(action aborted) and have different answer.
The folder/directory where I was uploading file did not have permission to upload file.
on Linux server you can run following command
chmod 777 files
When I gave permission to this directory, I did not get this error, and could upload file successfully.
I am running a centOS 6.9. chmod 0755 /server/php/files (rather than 777) and I changed the ownership (chown) over to apache. Ta-Da!

Categories