I am using following javascript code for uploading and for compressing images but it is working for only one image.
How to compress and then upload multiple images?
what modifications are required?
html:
<input id="fileupload" type="file" name="file" multiple>
javascript:
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$(function () {
'use strict';
var csrftoken = $.cookie('csrftoken');
var url = '/dashboard/{{name}}/{{name_product_type.type_product|urlencode}}/{{abc}}/';
$('#postbtn').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();
});
});
$('#fileupload').fileupload({
url: url,
crossDomain: false,
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
dataType: 'json',
uploadMultiple: true, // allow multiple upload
autoProcessQueue: false, // prevent dropzone from uploading automatically
maxFiles: 5,
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('#files');
$.each(data.files, function (index, file) {
var node = $('<p/>')
.append($('<span/>').text(file.name));
if (!index) {
node
.append('<br>')
// .append($('#postbtn').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(file.error);
}
if (index + 1 === data.files.length) {
data.context.find($('#postbtn').data(data));
// .text('Upload')
// .prop('disabled', !!data.files.error);
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}).on('fileuploaddone', function (e, data) {
$.each(data.result.files, function (index, file) {
var link = $('<a>')
.attr('target', '_blank')
.prop('href', file.url);
$(data.context.children()[index])
.wrap(link);
});
}).on('fileuploadfail', function (e, data) {
$.each(data.result.files, function (index, file) {
var error = $('<span/>').text(file.error);
$(data.context.children()[index])
.append('<br>')
.append(error);
});
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
I want to compress multiple images before uploading to the server. I am stuck with it please help.
Related
This is the image of form which I have designed in my project Now my requirement is to upload multiple files and with other form values over a single backend call.
<script>
<form class="form-horizontal" name="addColorForm" id="addColorForm"
enctype="multipart/form-data"
method="POST">
//Colour Name and Code fileds
//Files Uploader Plugin (Dropzone)
<input type="file" name="artworkFiles[]" style="visibility: hidden"/>
</form>
Now my script part
<script>
var validCode = function () { // my custom validation };
FormValidation.validators.validCode = validCode;
FormValidation.formValidation(
document.getElementById('addColorForm'),
{
fields: {
colorName: {
validators: {
notEmpty: {
message: '${message(code:"blank.error.message", default:"This field must be entered")}'
},
}
},
},
plugins: { //Learn more: https://formvalidation.io/guide/plugins
trigger: new FormValidation.plugins.Trigger(),
// Bootstrap Framework Integration
bootstrap: new FormValidation.plugins.Bootstrap(),
// Validate fields when clicking the Submit button
submitButton: new FormValidation.plugins.SubmitButton(),
// Submit the form when all fields are valid
// defaultSubmit: new FormValidation.plugins.DefaultSubmit(),
}
}
).on('core.form.valid', function () {
saveColor();
});
function saveColor() {
var url = "url";
var form = $("#createArtworkForm");
var formData = new FormData(form[0]);
$.ajax({
url: url,
type: 'POST',
enctype: 'multipart/form-data',
data: formData,
success: function (data) {},
cache: false,
contentType: false,
processData: false,
error: function () { }
});
}
var artworkColorsFiles = $('#kt_dropzone').dropzone({
url: "https://www.google.com", // Set the url for your upload script location
paramName: "media", // The name that will be used to transfer the file
maxFiles: 1,
maxFilesize: 40, // MB
addRemoveLinks: true,
acceptedFiles: "image/*",
autoProcessQueue: false,
accept: function (file) {
//Logic to add multiple files in an input type hidden which is declared above
let fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onloadend = function () {
let content = fileReader.result;
$('#artworkFiles').val(content);
file.previewElement.classList.add("dz-success");
}
file.previewElement.classList.add("dz-complete");
}
});
</script>
My questions is how to implement this or how should i add my all files(max 3) in a input type file field declared as visibility hidden.
The same I did in my project here is the code hope it will help you.
you have to use the dropzone function to send file and form data in sendingmultiple function you have to add a loop through your formdata enter code here
var data = $("form#OpportunityForm").serializeArray();
$.each(data, function (key, el) {
.append(el.name, el.value);
});
$(document).ready(function () {
zdrop = new Dropzone('#dropzone', {
url: '#Url.Action("SaveOpportunity", "Masters")',
maxFiles: 500,
maxFilesize: 300,
parallelUploads: 100,
addRemoveLinks: true,
autoProcessQueue: false,
uploadMultiple: true,
removeFilePromise: function () {
return new Promise((resolve, reject) => {
let rand = Math.floor(Math.random() * 3)
console.log(rand);
if (rand == 0) reject('didnt remove properly');
if (rand > 0) resolve();
});
},
sendingmultiple: function (file, xhr, formData) {
var data = $("form#OpportunityForm").serializeArray();
$.each(data, function (key, el) {
.append(el.name, el.value);
});
debugger
$("form#OpportunityForm").find("input[type=file]").each(function (index, field) {
const file = field.files[0];
formData.append('itemfile', file);
});
},
successmultiple: function (file, responseText) {
jQuery('form#OpportunityForm').find('textarea, input').each(function () {
jQuery(this).val('');
});
clear();
swal.fire("Opportunity Details Saved!", "Opportunity details Saved Successfully!", "success");
OpportunityMstList();
GetOpportunityMstList();
location.reload();
$("#myModal").modal('hide');
},
});
after adding this on the form submit button click you have to add this for creating blob file when you post data without image file.
jQuery(document).on('click', 'button#saveOpportunity', function (e) {
e.preventDefault();
if ($("#OpportunityForm").validate().form()) {
if (zdrop.files.length == 0) {
var blob = new Blob();
blob.upload = { 'chunked': zdrop.defaultOptions.chunking };
zdrop.uploadFile(blob); // just submit the form
} else if (zdrop.getRejectedFiles().length > 0) {
alert("The attached file is invalid");
} else {
zdrop.processQueue();
}
}
});
I´m using Dropzone.js but my option are not recognized at all. I tried to place the code different places, but I´m not sure where it should be placed. I read that the Dropzone.options must be out of document.ready or it wont work.
<form action="/" method="post" class="dropzone" id="my-dropzone"></form>
<script>
var myDropzone = new Dropzone("#my-dropzone");
// Disabling autoDiscover, otherwise Dropzone will try to attach twice.
Dropzone.autoDiscover = false;
Dropzone.options.myDropzone = {
paramName: 'photo',
acceptedFiles: '.jpg, .jpeg, .png',
maxFilesize: 1,
init: function() {
this.on("uploadprogress", function(file, progress) {
console.log("File progress", progress);
});
}
}
Maybe you can try this, I hope it helps.
Click here for the JSFiddle Demo.
Other alternative code, click here.
$(function() {
Dropzone.options.myDropzone = {
maxFilesize: 1,
addRemoveLinks: true,
dictResponseError: 'Server not Configured',
acceptedFiles: ".png,.jpg,.jpeg",
init: function() {
var self = this;
// config
self.options.addRemoveLinks = true;
self.options.dictRemoveFile = "Delete";
//New file added
self.on("addedfile", function(file) {
console.log('new file added ', file);
});
// Send file starts
self.on("sending", function(file) {
console.log('upload started', file);
$('.meter').show();
});
// File upload Progress
self.on("totaluploadprogress", function(progress) {
console.log("progress ", progress);
$('.roller').width(progress + '%');
});
self.on("queuecomplete", function(progress) {
$('.meter').delay(999).slideUp(999);
});
// On removing file
self.on("removedfile", function(file) {
console.log(file);
});
}
};
})
In my application I have added image upload fields dynamically using jquery append
So I use dropzone js and it not work when it append because it not initialize in document load.
So how could I load that dynamically
$(add_button).click(function(e){
$(wrapper).append(
'<div class="dropzone small-dropzone feedDropZone">' +
'<div class="dz-message" data-dz-message><p>Drop image or click to select</p></div></div>');
}
});
Dropzone code is
$('#add').on('click', '.feedDropZone', function(){
// do something here
Dropzone.autoDiscover = false;
var minImageWidth = 800, minImageHeight = 600;
$(this).dropzone({
url: base_url + "admin/feed/upload",
maxFiles: 1,
maxFilesize: 5,
acceptedFiles: ".jpeg,.jpg",
addRemoveLinks: true,
maxfilesexceeded: function (file) {
},
createImageThumbnails: true,
success: function (file, response) {
imgObject = JSON.parse(response);
},
error: function (file, response) {
},
init: function () {
this.on("thumbnail", function (file) {
if (file.width < minImageWidth || file.height < minImageHeight) {
file.rejectDimensions();
}else if(file.size/(1024*1024) > 5){
file.rejectFilesize();
}
else {
file.acceptDimensions();
}
});
}
});
});
I'm getting below error:
Error: No URL provided.
throw new Error("No URL provided.");
I am using dropzone for uploading files , I have set the file limitations upto maximum six files, this code is working if I upload one image at a time, but if I select more then six images by pressing control button at the start of uploading files then it does not validate the files and uploads all files. I am using laravel for backend, My code is:-
Dropzone.options.myAwesomeDropzone = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 1, // MB
maxFiles: 6,
acceptedFiles: ".jpeg,.jpg,.png,.gif",
clickable: true,
init: function () {
this.on("success", function(file, responseText) {
file.previewTemplate.setAttribute('id',responseText[0].id);
});
this.on("thumbnail", function(file) {
if (file.width < 350 || file.height < 200) {
file.rejectDimensions()
}
else {
file.acceptDimensions();
}
});
},
accept: function(file, done) {
file.acceptDimensions = done;
file.rejectDimensions = function() { done("Image width or height should be greater than 350*200"); };
},
removedfile: function(file){
var name = file.name;
$.ajax({
type: 'POST',
url: ajax_url+'listing/deleteListingImage/'+name,
dataType: 'html'
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
},
dictDefaultMessage: "Drop your files to upload"
}
Thanks
You can remove the extra files using the method removeFile(file) when maxfilesexceeded is called.
Like this:
Dropzone.options.myAwesomeDropzone = {
maxFiles: 2,
autoProcessQueue: false,
init: function(){
var myDropZone = this;
myDropZone.on('maxfilesexceeded', function(file) {
myDropZone.removeFile(file);
});
}
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.3.0/dropzone.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.3.0/min/dropzone.min.js"></script>
<form action="/file-upload"
class="dropzone"
id="my-awesome-dropzone">
</form>
http://output.jsbin.com/dodajij
I have some problems with Dropbox uploader in my Wordpress site.
It gives me 'Uncaught TypeError: Cannot call method 'submit' of undefined' on this lines:
$('#fileupload')
.bind('fileuploadstop', function (e, data) {
//window.location.href = 'http://hiphopsmurf.com';
$('#multimages', top.document).val(upfiles);
parent.document.forms["multi_image"].submit();
//parent.tb_remove();
});
Here is whole document code:
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload();
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
if (window.location.hostname === 'blueimp.github.com') {
// Demo settings:
$('#fileupload').fileupload('option', {
url: '//jquery-file-upload.appspot.com/',
maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
process: [
{
action: 'load',
fileTypes: /^image\/(gif|jpeg|png)$/,
maxFileSize: 20000000 // 20MB
},
{
action: 'resize',
maxWidth: 1440,
maxHeight: 900
},
{
action: 'save'
}
]
});
// Upload server status check for browsers with CORS support:
if ($.support.cors) {
$.ajax({
url: '//jquery-file-upload.appspot.com/',
type: 'HEAD'
}).fail(function () {
$('<span class="alert alert-error"/>')
.text('Upload server currently unavailable - ' +
new Date())
.appendTo('#fileupload');
});
}
} else {
$('#fileupload').fileupload('option', {
//maxFileSize: 5000000,
maxFileSize: 1048576,
//acceptFileTypes: /(\.|\/)(gif|jpe?g|png|psd)$/i,
acceptFileTypes: /(\.|\/)(doc|docx|gif|jpg|jpeg|pdf|png|psd|tif|tiff)$/i,
singleFileUploads: true,
sequentialUploads: true,
autoUpload: true,
});
var upfiles = "";
$('#fileupload')
//.bind('fileuploaddrop', function (e, data) {$.each(data.files, function (index, file) {alert('Added file: ' + file.name);});})
//.bind('fileuploaddrop', function (e, data) {$.each(data.files, function (index, file) { upfiles += file.name + ",";});})
.bind('fileuploaddone', function (e, data) {$.each(data.files, function (index, file) { upfiles += file.name + ",";});})
.bind('fileuploadchange', function (e, data) {/* ... */})
//fail: function (e, data) {data.submit();}
//.fileupload({fail: function (e, data) {alert('FAIL');}});
;
$('#fileupload')
.bind('fileuploadstop', function (e, data) {
//window.location.href = 'http://hiphopsmurf.com';
$('#multimages', top.document).val(upfiles);
parent.document.forms["multi_image"].submit();
//parent.tb_remove();
});
}
});
I'm kind a week in Java script, so will appreciate for any help.
Generally, when working with JavaScript / jQuery when you receive a "method is undefined" error there's an issue with your selector.
I would use a jQuery selector to submit the form. Try replacing the problem line with this:
$('#multi_image').submit();
(That assumes your form has an id attribute of "multi_image").