Dropzonejs how to add/delete from server? - asp.net-mvc

I know this is a very old issue but honestly I did not find a single complete piece of code for dropzonejs which is working as described.
I am trying to implement dropzonejs for file uploading. What I need is upload file to the server when it is dragged, and remove the file from the server when Remove file url is clicked.
I saw many solutions, for me, uploading just works fine. But when I try to implement the remove, I found no sample.
for the upload process, I configured my dropzone like below:
Dropzone.options.dropzoneForm = {
addRemoveLinks: true,
init: function() {
//upload process
}
};
It shows the addRemoveLink like "Remove file" just under the uploaded file.
I have seen someone to use another property like
Dropzone.options.dropzoneForm = {
addRemoveLinks: true,
removedFiles: function() {
//remove process
}
};
I am not sure how to implement this. Should I implement this like below? :
Dropzone.options.dropzoneForm = {
addRemoveLinks: true,
init: function(){
//upload process
}
removedFiles: function() {
//remove process
}
};
Please NB. I am expecting a full working example with server side upload and file delete.

Related

How to ZIP (compress) an SQLITE database file in Cordova?

I need a "support" mode for my Cordova app currently running on Windows Mobile and iOS. For this purpose, I need to compress an sqlite database file and upload it to a server. The database has to be compressed as it might grow over 250MB and the upload has to work without a wifi connection.
Searching the web brought up different approaches but all of them were outdated or did only solve my problem for either iOS or Windows Mobile. For example, when using the Cordova file plug-in I've encountered this in the plug-in documentation:
Supported Platforms
Android iOS OS X Windows* Browser
These platforms do not support FileReader.readAsArrayBuffer nor FileWriter.write(blob).
This was my approach: Cordova - Zip files and folders on iOS
Any ideas?
I would suggest you to give FileReader() a second chance.
In my case wich may be very similar to yours, I read a file using FilerReader.readAsArrayBuffer and after that, compress it using the JSZip library: http://stuartk.com/jszip
In opposition to the cordova-file-plugin's API documentation (https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/)
"Windows*"->"These platforms do not support FileReader.readAsArrayBuffer nor FileWriter.write(blob))"
I experienced that readAsArrayBuffer works under Windows UWP platform, but slower.
So in my case, with a file of approx. 50M I had to wait for nearly 2min for the whole process to finish!
Try following this example:
You'll need to adapt to your paths but this runs for WINDOWS UWP and IOS (didn't test it with Android but that was not your question).
Also, you'll need to implement your own error handler (errorHandler).
This solution uses Promises since you'll have to wait for the file beeing read and compressed.
PS1: Always be sure your "device ready's event" as been fired in order to access plugins.
PS2: You may encouter no access permission on the database file, this may be related to the fact, that it's being used by another process.
Be sure the database is closed.
SQLITE:
var sqlite = window.sqlitePlugin.openDatabase({ name: 'yourdb.db', location: 'default' });
sqlite.close(function () {
console.log("DONE closing db");
}, function (error) {
console.log("ERROR closing db");
console.log(JSON.stringify(error));
});
"ZIP" function:
function zipFile(sourceFileName, targetFileName) {
return new Promise(function (resolve, reject) {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
fs.root.getFile(sourceFileName, { create: false, exclusive: false }, function (fe) {
fe.file(function (file) {
var reader = new FileReader();
reader.onloadend = function (data) {
var zip = new JSZip();
zip.file(sourceFileName, data.target.result);
zip.generateAsync({
type: "blob",
compression: "DEFLATE",
compressionOptions: {
level: 9
}
// level 9 means max. compression
// this may also take some time depending on the size of your file
// I tested it with a 50M file, it took about 65 sec.
}).then(
// following is post-zip in order to transfer the file to a server
function (blob) {
fs.root.getFile(targetFileName, { create: true, exclusive: false }, function (newzip) {
writeFile(newzip, blob, "application/zip").then(function () {
var f = blob;
var zipReader = new FileReader();
zipReader.onloadend = function (theFile) {
var base64 = window.btoa(theFile.target.result);
resolve(base64);
};
// need to "resolve" the zipped file as base64 in order to incluse it in my REST post (server-upload)
zipReader.readAsBinaryString(f);
});
});
}
)
};
reader.readAsArrayBuffer(file);
// this may take some time depending on the size of your file
// I tested it with a 50M file, it took about 72 sec.
}, errorHandler);
}, errorHandler);
});
});
}
ex call:
if (window.cordova) {
document.addEventListener('deviceready', function () {
zipFile("yourDatabaseFileName.db","compressedDatabaseFile.zip");
});
}
Why not use sqlite ".dump" command as query and get result via steam and then compress the output. Even though text dump will be larger it will get reasonable size when you compress it. I think there are some very good text only compression algorithms as well,

Rails image upload with carrier wave

I successfully created a form for User model where i can upload image with carrier wave. This works nicely with submit button.
Everything is fine but i want to improve that with jquery file upload or something similar. So my imagination is i will click on file_upload button then select the file and after that it will preview the thumb of image.
I tried to follow railcast #381 but when i upload image, the preview will appear after refresh of page. Is it better to use js response or json? Is there a better way for ajax image upload? Thanks for advices
See the Attached : Then use the following code.
Clicking on the "Upload different file" will trigger the hidden file uploader.
$('#page3-upload-bg-picture-link').click(function(){
$("#page3-upload-bg-picture").trigger("click");
});
Then if you upload a file, it will call the change funcution.
$("#page3-upload-bg-picture").change(function(){
page3BgImage(this);
});
Then the page3BgImage is going to be called. Here, the image is read from the location and show in my image's "You Uploaded Image" div.
function page3BgImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#page3-preview-bg-image').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}

How to save Highcharts image on server auomatically

I am using highcharts and Ruby on Rails to creating chart. I want to save graph as server automatically. Following code download image automatically on download folder with name as chart.png
events: {
load: function () {
var ch = this;
setTimeout(function(){
ch.exportChart();
});
}
}
I want to save grph as /asset/image folder with name today_Report.png
I don't think you can force user to save anything in folder you want to. That's about path, now about name for file, check this, example:
chart.exportChart({ "filename": "today_Report" });

Rails Cloudinary Direct Image Upload After Commit

I have a question regarding direct-image-upload from Cloudinary. I could set this up in a rails app using simple-form and <% = f.cl_image_upload (: file)%> but after I select the file, it start uploading. I don't like this approach and I want that upload start just after commit the form. Is it possible? I worry about having file in Cloudinary server which does not have a corresponding id in my database.
The default implementation indeed automatically uploads a file once selected. Most users don't bother with deleting accidentally uploaded images as they don't take a lot of extra storage. However, if you wish not to upload the image automatically on selection, you can set the autoUpload to false in the fileupload call. For example:
$(document).ready(function() {
$('.cloudinary-fileupload').fileupload({
autoUpload: false
});
});
I think you can help me, Actually, I have this script...
<script>
$(document).ready(function() {
// Cloudinary jQuery integration library uses jQuery File Upload widget
// (see http://blueimp.github.io/jQuery-File-Upload/).
// Any file input field with cloudinary-fileupload class is automatically
// wrapped using the File Upload widget and configured for Cloudinary uploads.
// You can further customize the configuration using .fileupload method
// as we do below.
$(".cloudinary-fileupload")
.fileupload({
// Uncomment the following lines to enable client side image resizing and valiation.
// Make sure cloudinary/processing is included the js file
disableImageMetaDataLoad: true,
disableImageResize: false,
imageMaxWidth: 800,
imageMaxHeight: 800,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png|bmp|ico)$/i,
maxFileSize: 20000000, // 20MB
dropZone: "#direct_upload",
start: function (e) {
$(".status").text("Starting upload...");
},
progress: function (e, data) {
$(".status").text("Uploading... " + Math.round((data.loaded * 100.0) / data.total) + "%");
},
fail: function (e, data) {
$(".status").text("Upload failed");
}
})
.off("cloudinarydone").on("cloudinarydone", function (e, data) {
$(".status").text("");
$(".preview").html(
$.cloudinary.image(data.result.public_id, {
format: data.result.format, width: 150, height: 100, crop: "limit"
})
);
});
});
</script>
I'm beginning with javascript. This script above is working fine, but it just show me the preview after upload it. I don't like this approach because, if user change the preview image, I will have one file upload to Cloudinary without relative register in my db. Will be great if is possible show the preview and just upload after the user press submit in the form.
Note: I hope you understand me, I'm from Brazil and I don't write in english very well.

How to I preload existing files and display them in the blueimp upload table?

I am using the jquery-ui version of Blueimp upload and I like how I can format a table and display files that were just uploaded. But I'd like to use it as a file manager as well so I want to preload existing files and display than as if they were just uploaded. How can I do that? A sample link to where someone else has addressed this would suffice. BTW, I am uploading several different file types, not just images.
Thanks!
Or without an ajax call:
Prepare array containing details of existing files, e.g:
var files = [
{
"name":"fileName.jpg",
"size":775702,
"type":"image/jpeg",
"url":"http://mydomain.com/files/fileName.jpg",
"deleteUrl":"http://mydomain.com/files/fileName.jpg",
"deleteType":"DELETE"
},
{
"name":"file2.jpg",
"size":68222,
"type":"image/jpeg",
"url":"http://mydomain.com/files/file2.jpg",
"deleteUrl":"http://mydomain.com/files/file2.jpg",
"deleteType":"DELETE"
}
];
Call done callback
var $form = $('#fileupload');
// Init fileuploader if not initialized
// $form.fileupload();
$form.fileupload('option', 'done').call($form, $.Event('done'), {result: {files: files}});
I also had the same problem. It is not magic how it works. I recommend to examine the UploadHandler.php file. Then you will be able to modify this plugin accordind to your needs.
The code above in your second post is just an ajax call to the uploader script (by default index.php in server/php/ folder). The call method is set to "get" by default in $.ajax object.
Open the UploadHandler.php file and go to the class method "initialize(...)". You will see how the call with "get" handled. UploadHandler calls the class method this->get(.:.) to prepare and send the list of existing files. If you use other upload directory, you need pass a parameter to the UploadHänder. Simply chage the url property in the $.ajax object like :
url: $('#fileupload').fileupload('option', 'url')+'?otherDir='+myDir,
then you should initialize the option property of the UploadHandler before you create a new UploadHandler object like this:
$otherDir = trim($_REQUEST['otherDir']);
$otherDir_url = [anyURL] .'/'.$otherDir;//so that the files can be downloaded by clicking on the link
$options = array(
'upload_dir'=> $otherDir,
'upload_url'=> $otherDir_url,
);
$upload_handler = new UploadHandler($options);
Found the code in the main js file... It wasn't obvious how it worked. Got it working just fine.
// Load existing files:
$.ajax({
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).done(function (result) {
$(this).fileupload('option', 'done').call(this, null, {result: result});
});
If any of you looking at this is doing it in .NET, find this: (for me it is in application.js
For a fairly recent version, there is a function
// Load existing files:
$.getJSON($('#fileupload form').prop('action'), function(files) {
files = somethingelse;
var fu = $('#fileupload').data('fileupload');
fu._adjustMaxNumberOfFiles(-files.length);
fu._renderDownload(files)
.appendTo($('#fileupload .files'))
.fadeIn(function() {
// Fix for IE7 and lower:
$(this).show();
});
});
Inside the application.js
I'm doing it for .NET though, and actually needed this gone.
Then set your somethingelse to either your files or "" depending on what you want to show. If you remove the line files = somethingelse then it will preload all files from the folder.

Resources