Dropzone.js : add already stored files not triggering events - javascript

I'm using dropzone.js and node.js to add an easy drag-and-drop interface for a user to upload up to 10 photos to server.
Here is my init function:
init: function(){
var photos = $('#property-photo').data('photos').split(',');
for (var i = 0; i < photos.length; i++) {
var photo = "/photo/" + photos[i];
var mockFile= {type: "image/*", name: 'photo', size: 1500};
this.addFile.call(this, mockFile);
this.options.thumbnail.call(this, mockFile, photo);
}
}
The thumbnail is shown but when i call listingDropzone.processQueue(); - it throws an error:
Failed to execute 'append' on 'FormData': No function was found that
matched the signature provided.
Only if i remove the image and add a new one it works.
Any ideas?

Dropzone can't upload a mock file. Mock file was already uploaded.
You can see this issue: https://github.com/enyo/dropzone/issues/418

Related

Change image file name to unique using dropzone.js

I'm trying to make an image upload website using Dropzone.js.
I need to change the image to a unique name but I can only change the display name or the name that the image saves.
This the code that I got now:
Dropzone.options.fileupload = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 10, // MB
init: function() {
this.on('processingfile', function(file) {
file.name = 'test.jpg';
});
}
};
There is no clear way to do this.
Uploading multiple files with the same file.name using dropzone.js
Use processing event: (not working)
myDropone.on('processing', function(file) {
file.name = 'justin-bieber.jpg';
});

Saving an image to app properties

Hi I'm trying to save an image to the apps properties as part of a JSON array but when i try to display it, the imageview appears blank. The image is grabbed from the phone's gallery when the Upload_pic button is clicked. Code below:
Upload_pic.addEventListener('click', function (e){
Upload_pic.setImage('/images/uploadPhoto2.png');
Titanium.Media.openPhotoGallery({
success: function(e){
console.log("typeof e.media -------- " + e.media);
ImageView=Ti.UI.createImageView({
image:e.media
}).toImage();
},
error: function(e){
alert("Error accessing photos");
Upload_pic.setImage('/images/uploadPhoto1.png');
},
cancel: function(e){
Upload_pic.setImage('/images/uploadPhoto1.png');
},
alowEditing:true,
mediaType:[Titanium.Media.MEDIA_TYPE_PHOTO]
});
});
and then I'm saving the image on this submit_btn click:
Submit_btn.addEventListener('click', function (e){
var filename = ID+"-ea.jpg";
bgImage = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, filename);
bgImage.write(ImageView);
if (bgImage.exists()) //File ever does not exist.
{
alert('file '+filename+' exists!!!');
// I am getting this alert
}
else
{
alert('file '+filename+' IS NOT exist(');
}
MyRecipe_info= {name: title_textField.value, ID:ID, Ingredients: ingredients_textField.value, numSteps:numSteps_textField.value, pic:bgImage, steps:numStepsArray};
Ti.App.Properties.setBool('MyRecipeAdded', true);
MyRecipes_data.push(MyRecipe_info);
Ti.App.Properties.setString('MyRecipesData', JSON.stringify(MyRecipes_data));
alert("Recipe added successfully!");
});
And then i am displaying it here:
MyRecipes_data=JSON.parse(Ti.App.Properties.getString('MyRecipesData'));
for(i=0;i<MyRecipes_data.length;i++){
var Pic = Titanium.UI.createImageView({
left: '5dp',
top:'20dp',
right:'15dp',
height: Ti.UI.SIZE,
bottom: '5dp',
image:MyRecipes_data[i].pic
});
}
Currently working on iOS, but code will need to work on Android in future. Using Titanium SDK 3.3.0.201407100905 and Titanium Classic
Problem was I needed to store the bgImage.nativePath
to store a image in property is bad habit as it takes much memory specially for android so i would suggest to store only image path in that array
or even if possible you should use database to store data instead of using Ti.Property.
Hope you get it.

Download images on client to zip

Okey, so what I want to do is download multiple images stored in an JavaScript array in AngularJS. I have not found any way of doing this in the form of "pure" images like .png .jpg etc (although if anyone knows how to do this please let me know). So I have turned to trying to zip the images with the help of jszip.js according to the description here : http://viralpatel.net/blogs/create-zip-file-javascript/
<li ng-click="download()"><a>Save to harddrive</a></li>
So this is the code called when the user clicks "download":
photodice.controller('ProjectController', function($scope, imageFactory) {
$scope.images = imageFactory.getImages();
$scope.download = function() {
var zip = new JSZip();
for (var x in $scope.images) {
zip.folder("images").add("image" + x + ".png", $scope.images[x], {base64: true});
}
var content = zip.generate();
console.log("content = "+ content);
location.href="data:application/zip;base64," + content;
}
});
The problems occurs when the last line of code is executed, the browser crashes... I do not really understand how filedownloads work... Any suggestion or tips on what I should read up on would be greatly appreciated!
Update:
I tried using Downloadify to solve my problem... and added some code:
$scope.download = function() {
var zip = new JSZip();
for (var x in $scope.images) {
zip.folder("images").add("image" + x + ".jpg", $scope.images[x], {base64: true});
}
Downloadify.create('downloadify',{
filename: function(){
return "Images.zip";
},
data: function(){
return zip.generate();
},
onComplete: function(){
alert('Your File Has Been Saved!');
},
onCancel: function(){
alert('You have cancelled the saving of this file.');
},
onError: function(){
alert('You must put something in the File Contents or there will be nothing to save!');
},
transparent: false,
swf: 'downloadify.swf',
downloadImage: 'img/download.png',
width: 100,
height: 30,
transparent: true,
append: false,
dataType: 'base64'
});
And now I can save the zip file:)
HOWEVER I still have a problem... the files in the zip are corrupt...
Normal non corrupt images look like this:
"data:image/jpeg;base64,iVBORw0KGgoAhE... ...c8+ocAAAAORK5CYII="
If I upload "currupt" images to my site agian and check the scope of the images that are corrupt the data looks like this:
"data:image/jpeg;base64,dataimage/jpegbase64iVBORw0KA... ...RNgAK5CYII="
Alternatively I remove the {base64: true}:
"data:image/jpeg;base64,ZGF0YTppbWF... ...WT1JLNUNZSUk9" (no "=" at the end)
What can I do about this?
I'm putting the answer here for future reference (because it was buried in the comments).
The issue comes from $scope.images[x] which contains a string, "data:image/jpeg;base64,iVBORw0KGgoAhE... ...c8+ocAAAAORK5CYII=". JSZip interprets the data:image/jpeg;base64, part as base64 content and generates corrupted images. To remove this part, you can do the following :
var base64 = $scope.images[x];
var index = base64.indexOf(",");
if (index !== -1) {
base64 = base64.substring(index + 1, base64.length);
}
zip.folder("images").file("image" + x + ".jpg", base64, {base64: true});
Also, the add() method you use has been deleted in 2011 so you may want to update JSZip ! (but that may need some work : only folder() and remove() haven't changed between your version and the latest).

Dropzonejs mulitple zones with file preview

Hoping that someone will be able to tell me where Im going wrong here .
Im using Dropzonejs to allow people to drop files for storage online, I have 8 zones on one page, each used for a different category, when someone drops a file they are saved with additional data depending on which zone they were dropped in for later retrieval .. this all works fine.
I then wanted each zone to show the thumbnails for each of the files on the server under its category on page refresh, this is where I get problems, using the follwing code I get all my files being shown in the bottom zone, and the others are empty. Its obviously a problem with the code that fetches current files and makes the thumbnails, but Im lost as to why.
If I only have one instance on a page it all works fine.
Heres the code I use to setup and instantiate each dropzone instance.
Dropzone.options.dzdiag = {
url: "upload.php",
previewsContainer: "#dzdiag",
init: function() {
thisDropzone = this;
filetype = "diagnostic";
var propid = <?php echo $id; ?>; // set value to current property id
$.get('upload.php?propid='+propid+'&filetype='+filetype, function(data) { // get exisitng files and thumbnail
$.each(data, function(key,value){
var mockFile = { name: value.name, size: value.size, fileid: value.fileid, };
thisDropzone.options.addedfile.call(thisDropzone, mockFile);
var pattern = /\.(gif|jpg|jpeg|tiff|png)$/i;
if( pattern.test(value.name)){
thisDropzone.options.thumbnail.call(thisDropzone, mockFile, "uploads/"+value.name);
}
});
});
thisDropzone.on("sending", function(file, xhr, formData) {
formData.append("propid", propid);
formData.append("filetype", filetype);
});
thisDropzone.on("success", function(file, serverack) {
file.fileid = serverack;
});
thisDropzone.on("removedfile", function(file) {
var delid = file.fileid;
$.post('upload.php?delid='+delid);
});
}
};
$("#dzdiag").dropzone();
Simply changing the previewsContainer (on not specifying it) for each zone should get you what you want.

Validate image filetype/filesize, crop, resize & then upload

I'm looking for a client side solution to validate whether the image being uploaded is of accepted file type, file size & then crop the image as directed by user, re-size it to fit within some particular dimensions & then upload the re-sized & optimized image to server.
Are there any well known open-source libraries that can help me implement this ? (Multiple files uploading not needed). I'm not wanting to implement this myself & looking for a library that can provide a cross browser compatible solution with fallbacks for old/unsupported browsers.
I came across plupload & agile uploader, but those don't help in cropping images as per user directions.
Using jQuery 1.7. Open to add other libraries too in case required.
peace be upon you brother
i'm using what you want in my project but no ( resize photo as i put custom size for images )
i using ( imgareaselect ) to crop photo
but i don't remember the site of it, maybe: http://odyniec.net/projects/imgareaselect/examples.html
if is it that site right, i'm using this code
var x1 = null, y1 = null, w = null, h = null, Signal = null, object=null;
function preview(img, selection) {
var img = {
url: jQuery("#image").attr("src"),
width: jQuery("#image").width(),
height: jQuery("#image").height()
}
var scaleX = 128 / selection.width; // 128 = my custom size ;)
var scaleY = 128 / selection.height;
$(".avatar-box img").replaceWith('<img id="thumbnail" src="'+img.url+'" class="preview" border="0"/>');
$('#thumbnail').css({
width: Math.round(scaleX * img.width) + 'px',
height: Math.round(scaleY * img.height) + 'px',
marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
});
x1 = selection.x1; y1 = selection.y1; w = selection.width; h = selection.height;
}
$(window).ready(function () {
$('#image').imgAreaSelect({ aspectRatio: '1:1', onSelectChange: preview });
});
and to check the size and type: i use also this script
$("form").submit(function(){
var OrgFile = $(this).find("[type=file]"),
FileName = OrgFile.val(),
FileExtension = FileName.split('.').pop().toLowerCase();
if(FileName.indexOf(".")==-1 || FileExtension != "jpg" && FileExtension != "jpeg" && FileExtension != "png" && FileExtension != "gif" ){ // Curstom File Extension
alert("This isn't a Photo !");
return false;
}else
if((OrgFile[0].files[0].size/1024/1024) > (1)){ // Max Photo Size 1MB
alert("You Photo is too big !");
return false;
}else{
alert("every thing Fine :)");
return true;
}
});
Then if the client submit the cropped image
$('#create_thumbnail').submit(function() {
$.ajax({
type : "POST",
url : "resize.php",
data : {logged_code: logged_code,x1: x1,y1: y1,w: w,h: h},
success: function(data) {}
});
return false;
});
And resize.php file
function resizeThumbnailImage($thumb_image_name, $image, $width, $height, $start_width, $start_height, $scale){
list($imagewidth, $imageheight, $imageType) = getimagesize($image);
$imageType = image_type_to_mime_type($imageType);
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
switch($imageType) {
case "image/gif":
$source=imagecreatefromgif($image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
$source=imagecreatefromjpeg($image);
break;
case "image/png":
case "image/x-png":
imagealphablending($newImage, false);
imagesavealpha($newImage, true);
$source=imagecreatefrompng($image);
break;
}
imagecopyresampled($newImage,$source,0,0,$start_width,$start_height,$newImageWidth,$newImageHeight,$width,$height);
switch($imageType) {
case "image/gif":
imagegif($newImage,$thumb_image_name);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
imagejpeg($newImage,$thumb_image_name,100);
break;
case "image/png":
case "image/x-png":
imagepng($newImage,$thumb_image_name);
break;
}
chmod($thumb_image_name, 0777);
return $thumb_image_name;
}
i hope that i help you and understand your question,
please vopte my answer that i want to join php chat room to find one help me in a problem
sorry for my bad english i'm speaking arabic
Resizing can be done with FileReader and a canvas.
Create a canvas with wanted size.
Load the image. Then use the canvas.toDataURL(fileType) to get the file content as base64
Try using Fine Uploader for the client side validation and uploading; with JCrop for the cropping of the image afterwards.
Fine uploader is excellent for restricting the size and file type (See here) on the client side; however it does depend on which browsers you need to support (I believe IE7 won't allow you to validate on the client side like this).
Whilst JCrop is an easy to implement cropping tool which supports aspect ratios and converting images between their display and actual sizes.
There are several separate things here:
Validating image/file type. This can be done at the client side, but you will need to do it at the server again for security. For a file input that only accepts images, you can use:
<input type="file" accept='image/*'>
Letting the user crop the image. There are several libraries here, the most prominent one being Jcrop. But there are alternatives, like imgareaselect, jqCrop and jquery-cropbox (I created and mantain the jquery-cropbox). See here for a very minimal example on how you can get started with one or two lines of jquery.
http://acornejo.github.io/jquery-cropbox/
Doing the actual cropping at the client. This requires HTML5, and therefore won't work with older version of internet explorer. In particular you will need the canvas api, and possibly the file api (to serve the files). jquery-cropbox can also do this for you through the getBlob and getDataURL methods. If you want to do it by hand, take a look here:
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D
Uploading the image. There are plenty of scripts for uploading images out there, take your pick. If you are using jquery-cropbox, then you can use jquery to handle the upload to your server like this (uploading client generated form data like this will also require an HTML5 compliant browser).
var blob = $('#yourimage').data('cropbox').getBlob();
var fd = new FormData();
fd.append('file', blob);
$.ajax({
type: 'POST',
url: 'http://yourwebsite.com/handle_uploads',
data: fd,
cache: false,
contentType: false,
processData: false,
success: function(data){
alert('upload succeeded');
},
error: function () {
alert('upload failed');
}
});
},
jQuery Ajax code
jQuery('document').ready(function(){
var input = document.getElementById("imagefile");
var formdata = false;
if (window.FormData) {
formdata = new FormData();
}
input.addEventListener("change", function (evt) {
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
//validation to check whether uploaded files are images
if (!!file.type.match(/image.*/)) {
if ( window.FileReader ) {
reader = new FileReader();
reader.onloadend = function (e) {
};
reader.readAsDataURL(file);
}
if (formdata) {
//send the ajax query to upload the file(s)
jQuery.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (result) {
jQuery('div#response').html("Successfully uploaded").fadeOut();
}
});
}
}
else
{
alert('Not a vaild image!');
}
}
}, false);
});
HTML Code
<form enctype="multipart/form-data">
<input id="imagefile" type="file" name="image" accept="image/*"/ />
</form>
What above code will do for you is, once you upload the file(s) it will 1st of validate the type of the image and upload it via ajax for you. You can do multiple file uploads if you need. If you ever wonder what FormData does,
The FormData object lets you compile a set of key/value pairs to
send using XMLHttpRequest. Its primarily intended for use in sending
form data, but can be used independently from forms in order to
transmit keyed data. The transmitted data is in the same format that
the form's submit() method would use to send the data if the form's
encoding type were set to "multipart/form-data".
What addEventListener does for you is,
addEventListener() registers a single event listener on a single
target. The event target may be a single element in a document, the
document itself, a window, or an XMLHttpRequest.
You can use upload.php to upload the file(s) at the server level.
If you want to have the this functionality in a plugin you can extend the plugin with the above code and it will not brick your plugin because this is a very straight forward code snippet which gets the job done. I have successfully integrated the code to a plugin with no issues at all.
this link will show you how to validate for the file size. JavaScript file upload size validation
Re-size it to fit within some particular dimensions
javascript Image Resize
How to resize images proportionally / keeping the aspect ratio?
These link should help for you. I'm not going to integrate all into one because to maintain the simplicity of the code so you can understand easily.
If you have any issues let me know.
As for the file type and size:
var fileUpload = $(':file[id="fileUploadId"]');
var fileName = $(fileUpload).val();
// Checking type:
if(fileName.indexOf('.jpg') || fileName.indexOf('.gif')){/* Accepted types */}
// Check size
if($(fileUpload).size() <= yourAcceptedSize) {/* Accepted size */}
Please use the following to check filesize on client end:
<script type="text/javascript">
$('#image-file').bind('change', function() {
alert('This file size is: ' + this.files[0].size/1024/1024 + "MB");
});
</script>
If you need a plugin type to use for the entire project you can take a look at this.
If you are looking for a multiple uploader please use this.
Please have a look at this library
and this is documentation page
where you can set max resize values,
<maxwidth>800</maxwidth>
<maxheight>500</maxheight>
<minwidth>100</minwidth>
<minheight>70</minheight>
I have an idea.
You can try using this plugin to upload.
http://des.delestesoft.com:8080/?go=2
when you define the attributes: post variables->
variables:{
sessionID:"abcdefg",
width:$("#myimage").width(),
height:$("#myimage").heigth()
},
in the server side: you get the file and change the size image according the post variables.

Categories