I'm using jquery file upload in conjunction with summernote to upload images. I know jquery file-upload is supposed to re size large images to a max of 1920 x 1080 as a default but this isn't happening in my case. Here's my current setup:
$('#summernote').summernote({
height: 500,
minHeight: 300,
onImageUpload: function(files, editor, welEditable) {
uploadFile(files, editor, welEditable);
}
});
$('#fileupload').fileupload({
url: site_root + '/photos/index.php',
dataType: 'json',
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
maxFileSize: 8000000,
imageMaxWidth: 1920,
imageMaxHeight: 1080,
imageCrop: true
});
function uploadFile(files, editor, welEditable) {
if (files == null) {
return;
}
$('#fileupload').fileupload('send', {files: files})
.success(function (result, textStatus, jqXHR) {
//
});
});
}
I've even added image maxWidth/Height params but the images fail to be re sized. The image sizing works when I use jquery file upload in other areas but when using the send call it fails to resize them.
Is this a bug or am I missing something obvious?
Thanks,
-Paul
Are you including the extra required JS files listed on here?
https://github.com/blueimp/jQuery-File-Upload/wiki/Client-side-Image-Resizing
If so, it looks like you need to set "disableImageResize: false"
Related
I am experiencing an issue with DropZone JS Grabbing an input value and passing it along to the upload script. The upload is working and everything is fine EXCEPT this field not sending in the POST.
I have a very basic DZ config:
$("#file_uploader").dropzone({
url: '/ajax/upload.php',
dictDefaultMessage: 'Drop photos or click here to upload',
maxFilesize: 400000,
params: {'project': $('#project-name').val()}, // This is the part I am having issues with
success: function (file, response) {
var obj = JSON.parse(response);
if (obj.status === 'success') {
console.log('gtg');
} else {
alert('upload failed');
$(".dz-preview").remove();
}
}
});
I have a field in my html that looks like:
<input type="text" id="project-name" required="required"
class="form-control col-md-6 col-xs-12 limited_form"
placeholder="Project Name">
If I simply overwrite 'project': $('#project-name').val() to look like:
'project': 'test'
It works. So it's a matter of Dropzone not being able to "see" that input field for some reason.
I thought it might be the dash in the id project-name -- But according to the rules in HTML5 dashes are allowed in Ids.
There are no errors in the console, and this:
// Testing if Selector is working
$(document).on('keyup', '#project-name', function () {
console.log( $('#project-name').val() );
});
displays the project-name contents in the console correctly as I type them, so I know my selector is OK. Thus, my confusion on why DropZone isn't "seeing" it.
Why is DropZone "ignoring" my jQuery identified by selector id? Am I missing something glaringly wrong?
UPDATE
It is worth noting that my config lies within a $(document).ready(function () { -- However I have tried it both inside, and outside the function and still the problem persists.
Your dropzone script was probably trying to retrieve the value before the element is loaded on the DOM. Loading your script inside a $( document ).ready() function would be one way to go about it. Another way would be to just assign the script to a variable and then referencing the variable in dropzone like this:
$("#file_uploader").dropzone({
url: '/ajax/upload.php',
dictDefaultMessage: 'Drop photos or click here to upload',
maxFilesize: 400000,
params: {'project': function() {
var x = $('#project-name').val();
return x;
}},
success: /* some function */
});
You can also try to directly return the input value within the function and see if that works.
$("#file_uploader").dropzone({
url: '/ajax/upload.php',
dictDefaultMessage: 'Drop photos or click here to upload',
maxFilesize: 400000,
params: {'project': function() {
return $('#project-name').val();
}},
success: /* some function */
});
I want to use dropzone to display thumbnails of images that I already have on the server. I am creating a CMS for a property website. The server has images associated with Sites of properties. When the page loads, the init function of my dropzone displays the relevant image for a given site as a thumbnail in the dropzone.
There is a drop down box on the page which lets the user select another site. When they do this I want the dropbox object to basically do what's in the init function again. Make a call to the server and display the thumbnails that are associated with this different site.
I haven't been able to get a solution yet (obviously). Typically I will get something like, "dropzone still attached" with stuff I have tried. I can't seem to see anything in the docs that is useful.
Any help would be appreciated :)
//my dropzone object
var myDropzone = $('#featured-development-dropzone').dropzone({
url: '#Url.Action("SaveFeaturedDevelopmentImage","Homepage")',
maxFiles: 1,
addRemoveLinks: true,
init: function () {
var myDropzone = this;
$("select").on('click', function () {
myDropzone.removeAllFiles(true);
});
var siteID = $('#siteDropdown').find(':selected').val();
$.ajax({
url: '#Url.Action("GetFeaturedDevelopmentImage", "Homepage")',
data: { siteID: siteID },
type: 'GET',
success: function (data) {
console.log(data);
if (data.data != null) {
var mockFile = {
name: data.filename,
size: data.fileSize
};
// Call the default addedfile event handler
myDropzone.emit("addedfile", mockFile);
console.log(typeof (data));
// And optionally show the thumbnail of the file:
myDropzone.emit("thumbnail", mockFile, "data:image/png;base64," + _arrayBufferToBase64(data.data));
myDropzone.emit("complete", mockFile);
}
}
});
this.on("sending", function (file, xhr, formData) {
formData.append("SiteID", siteID);
formData.append("imageTypeID", 4);
console.log(formData);
});
}
});
var prevSiteID;
$("select").on('click', function () {
prevSiteID = this.value;
}).change(function () {
var newSIteID = this.value;
// potentially put code here that will reinitialize the dropbox and display images associated with different site.
console.log(prevSiteID);
console.log(newSIteID);
changeFeaturedDevelopment(prevSiteID, newSIteID);
I belive you need to recall that function again. Since when you are triying to attach a new image, the dropzone zone is already defined in the page load. Or you call the init again or try to reset it, so the dropzone can reattach another image.
I'm trying to alert the user when their files have been successfully uploaded but am stuck on getting it to work after the init function.
Here is my script:
<script>
Dropzone.options.myDropzone = {
paramName: 'file',
maxFilesize: 10, // MB
maxFiles: 20,
acceptedFiles: ".jpeg,.jpg,.png,.gif,.pdf,.doc,.docx,.xlsx,.xls",
};
this.on("successmultiple", function (file) {
alert("All files have uploaded ");
});
</script>
The upload does work so I am assuming it is how I am calling the successmultiple portion.
I ended up realizing that I needed to use: queuecomplete rather, which was the more appropriate option instead. (See: http://www.dropzonejs.com/#events)
I am using Dropzonejs to add image upload functionality in a Form, as I have various other fields in form so I have set autoProcessQueue to false and Processing it on click on Submit button of Form as shown below.
Dropzone.options.portfolioForm = {
url: "/user/portfolio/save",
previewsContainer: ".dropzone-previews",
uploadMultiple: true,
parallelUploads: 8,
autoProcessQueue: false,
autoDiscover: false,
addRemoveLinks: true,
maxFiles: 8,
init: function() {
var myDropzone = this;
this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
}
}
This works fine and allows me to process all images sent when form is submitted. However, I also want to be able to see images already uploaded by user when he edits the form again. So I went through following post from Dropzone Wiki.
https://github.com/enyo/dropzone/wiki/FAQ#how-to-show-files-already-stored-on-server
Which populates dropzone-preview area with existing images but it does not send existing images with form submit this time. I guess this is because theses images are not added in queue but If it's so then how can update on server side, In case an existing image is removed by user?
Also, what would be the better approach, add already added images in queue again or just send information of removed file?
I spent a bit of time trying to add images again, but after battling with it for a while I ended up just sending information about the deleted images back to the server.
When populating dropzone with existing images I attach the image's url to the mockFile object. In the removedfile event I add a hidden input to the form if the file that is being removed is a prepopulated image (determined by testing whether the file that is passed into the event has a url property). I have included the relevant code below:
Dropzone.options.imageDropzone = {
paramName: 'NewImages',
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
init: function () {
var myDropzone = this;
//Populate any existing thumbnails
if (thumbnailUrls) {
for (var i = 0; i < thumbnailUrls.length; i++) {
var mockFile = {
name: "myimage.jpg",
size: 12345,
type: 'image/jpeg',
status: Dropzone.ADDED,
url: thumbnailUrls[i]
};
// Call the default addedfile event handler
myDropzone.emit("addedfile", mockFile);
// And optionally show the thumbnail of the file:
myDropzone.emit("thumbnail", mockFile, thumbnailUrls[i]);
myDropzone.files.push(mockFile);
}
}
this.on("removedfile", function (file) {
// Only files that have been programmatically added should
// have a url property.
if (file.url && file.url.trim().length > 0) {
$("<input type='hidden'>").attr({
id: 'DeletedImageUrls',
name: 'DeletedImageUrls'
}).val(file.url).appendTo('#image-form');
}
});
}
});
Server code (asp mvc controller):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ViewModel viewModel)
{
if (ModelState.IsValid)
{
foreach (var url in viewModel.DeletedImageUrls)
{
// Code to remove the image
}
foreach (var image in viewModel.NewImages)
{
// Code to add the image
}
}
}
I hope that helps.
To extend on Teppic's answer, I found you needed to emit the complete event to remove the progress bar on the preview.
var file = {
name: value.name,
size: value.size,
status: Dropzone.ADDED,
accepted: true
};
myDropzone.emit("addedfile", file);
myDropzone.emit("thumbnail", file, value.path);
myDropzone.emit("complete", file);
myDropzone.files.push(file);
just use myDropzone.addFile(file)
from dropzone source code https://github.com/enyo/dropzone/blob/4e20bd4c508179997b4b172eb66e927f9c0c8564/dist/dropzone.js#L978
There's an official FAQ for that here
I solved this using the dropzone's built in "displayExistingFile" method.
in your init: function.
Create the mockfile
let mockFile = { name: file.title, size: file.size, dataURL:};
Call the displayExistingFile function
this.displayExistingFile(mockFile, , null, 'anonymous')
Instead of 'null' you can place a callback to respond to the thumbnail load event.
The 'anonymous' is for the cross origin property.
Originally I was doing this to programmatically upload a pre-existing file:
myDropzone.emit("addedfile", imageFile);
myDropzone.emit("thumbnail", imageFile, imageUrl);
myDropzone.files.push(file);
However, referencing this Dropzone Github Issue I found an easier way to directly upload:
myDropzone.uploadFiles([imageFile])
Unfortunately there are no references to this uploadFiles method in the Dropzone Documentation, so I figured I'd share some knowledge with all you Dropzone users.
Hope this helps someone
If you have the URL of the file, you can add the file with addFile.
fetch("url")
.then(res => res.blob())
.then((currentBlob) => {
const generateFile = new File([currentBlob], "filename.jpg", {
type: currentBlob.type,
});
myDropzone.addFile(generateFile);
});
On click of upload files just clear the files from dropzone.
All Files can be cleared using removeAllFiles() or specific file also you can delete by using removeFile(fileName).
I've written the following code to upload a file from a web browser. It works in Firefox but not Safari, are there any obvious reasons why this might be the case.
// when the file field is changed I get its data and the "salonId" variable
$("#btnFrontUpload").change(function (e){
frontPic = e.target.files[0]
displayPicAsBackground(frontPic, "btnFrontUploadShow")
frontPicName = frontPic.name
salonId=$("#salonId").val();
});
fd = new FormData()
$("#btnNextPhotos").click(function(){
$('#mdlPhotos').modal('hide')
resizeAndPopulateVariables()
doAjaxRequest()
});
});
function updateMilliTime(){
milliTime = (new Date).getTime()
}
function displayPicAsBackground(file, btn){
// here I display the uploaded file (which is a picture) on the screen
// it works on most browsers including mobile safari, but not the "desktop" safari
$.canvasResize(file,
{
width: 160,
height: 0,
crop: false,
quality: 100,
callback: function (data)
{
$('#'+btn).css("background", "url("+data+")")
}
});
}
function resizeAndPopulateVariables(){
// I resize the image and create a file variable for upload
$.canvasResize(frontPic,
{
width: 400,
height: 0,
crop: false,
quality: 100,
callback: function (data)
{ // Add file data
var frontPicForUpload = $.canvasResize('dataURLtoBlob', data)
fd.append("frontPic", frontPicForUpload)
fd.append("frontPicName", frontPicName)
fd.append("salonId", salonId)
}
});
}
function doAjaxRequest(){
// send the ajax request
$.ajax(
{
url: '/create/picture',
type: 'POST',
data: fd, //fd is a global variable
dataType: 'json',
contentType: false,
processData: false,
beforeSend: function (xhr)
{
xhr.setRequestHeader("pragma", "no-cache");
}
}
).done(function (response){
window.location.reload()
});
I don't really know your issue here maybe is your Ajax cal, so why not use a plugin Ajax . I know this sounds depressive.
here is a sample is so easy:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
</script>
</head>
There are many syntax errors in your code. I'm not sure how it runs in Firefox. Run your code through a Javascript code checker, like JSLint. The obvious one is that you don't have semicolons (;) at the ends of your lines. Add them.
The biggest one though is this segment:
$("#btnNextPhotos").click(function(){
$('#mdlPhotos').modal('hide');
resizeAndPopulateVariables();
doAjaxRequest();
}); // <--- what is this closing?
});
It looks like you meant to call .modal() with a callback function because you have a closing )} after doAjaxRequest(). I'm not familiar with the .modal() function, but it either needs to have a callback, perhaps like this:
$("#btnNextPhotos").click(function(){
$('#mdlPhotos').modal('hide', function () {
resizeAndPopulateVariables();
doAjaxRequest();
});
});
Or you need to remove the extra closing operators:
$("#btnNextPhotos").click(function(){
$('#mdlPhotos').modal('hide');
resizeAndPopulateVariables();
doAjaxRequest();
});