fineuploader setname with options - fine-uploader

I am trying to renname a file using fine uploader and the change keeps getting ignored
$(this).fineUploader({setName: {id: new_name}});
new_name of course was set earlier.
This seems to be correct and doesn't throw an error but just doesn't work.
Any ideas

The setName function can be called from jQuery using the below syntax. Note that we are plugging into the onSubmit event in order to obtain an id of a file which setName requires.
var $uploader =
$(this).fineUploader({
})
.on("submit", function (event, fileId, fileName) {
$uploader.fineUploader("setName", fileId, new_name);
});

Related

Getting file contents when using DropzoneJS

I really love the DropZoneJS component and am currently wrapping it in an EmberJS component (you can see demo here). In any event, the wrapper works just fine but I wanted to listen in on one of Dropzone's events and introspect the file contents (not the meta info like size, lastModified, etc.). The file type I'm dealing with is an XML file and I'd like to look "into" it to validate before sending it.
How can one do that? I would have thought the contents would hang off of the file object that you can pick up on many of the events but unless I'm just missing something obvious, it isn't there. :(
This worked for me:
Dropzone.options.PDFDrop = {
maxFilesize: 10, // Mb
accept: function(file, done) {
var reader = new FileReader();
reader.addEventListener("loadend", function(event) { console.log(event.target.result);});
reader.readAsText(file);
}
};
could also use reader.reaAsBinaryString() if binary data!
Ok, I've answer my own question and since others appear interested I'll post my answer here. For a working demo of this you can find it here:
https://ui-dropzone.firebaseapp.com/demo-local-data
In the demo I've wrapped the Dropzone component in the EmberJS framework but if you look at the code you'll find it's just Javascript code, nothing much to be afraid of. :)
The things we'll do are:
Get the file before the network request
The key thing we need become familiar with is the HTML5 API. Good news is it is quite simple. Take a look at this code and maybe that's all you need:
/**
* Replaces the XHR's send operation so that the stream can be
* retrieved on the client side instead being sent to the server.
* The function name is a little confusing (other than it replaces the "send"
* from Dropzonejs) because really what it's doing is reading the file and
* NOT sending to the server.
*/
_sendIntercept(file, options={}) {
return new RSVP.Promise((resolve,reject) => {
if(!options.readType) {
const mime = file.type;
const textType = a(_textTypes).any(type => {
const re = new RegExp(type);
return re.test(mime);
});
options.readType = textType ? 'readAsText' : 'readAsDataURL';
}
let reader = new window.FileReader();
reader.onload = () => {
resolve(reader.result);
};
reader.onerror = () => {
reject(reader.result);
};
// run the reader
reader[options.readType](file);
});
},
https://github.com/lifegadget/ui-dropzone/blob/0.7.2/addon/mixins/xhr-intercept.js#L10-L38
The code above returns a Promise which resolves once the file that's been dropped into the browser has been "read" into Javascript. This should be very quick as it's all local (do be aware that if you're downloading really large files you might want to "chunk" it ... that's a more advanced topic).
Hook into Dropzone
Now we need to find somewhere to hook into in Dropzone to read the file contents and stop the network request that we no longer need. Since the HTML5 File API just needs a File object you'll notice that Dropzone provides all sorts of hooks for that.
I decided on the "accept" hook because it would give me the opportunity to download the file and validate all in one go (for me it's mainly about drag and dropping XML's and so the content of the file is a part of the validation process) and crucially it happens before the network request.
Now it's important you realise that we're "replacing" the accept function not listening to the event it fires. If we just listened we would still incur a network request. So to **overload* accept we do something like this:
this.accept = this.localAcceptHandler; // replace "accept" on Dropzone
This will only work if this is the Dropzone object. You can achieve that by:
including it in your init hook function
including it as part of your instantiation (e.g., new Dropzone({accept: {...})
Now we've referred to the "localAcceptHandler", let me introduce it to you:
localAcceptHandler(file, done) {
this._sendIntercept(file).then(result => {
file.contents = result;
if(typeOf(this.localSuccess) === 'function') {
this.localSuccess(file, done);
} else {
done(); // empty done signals success
}
}).catch(result => {
if(typeOf(this.localFailure) === 'function') {
file.contents = result;
this.localFailure(file, done);
} else {
done(`Failed to download file ${file.name}`);
console.warn(file);
}
});
}
https://github.com/lifegadget/ui-dropzone/blob/0.7.2/addon/mixins/xhr-intercept.js#L40-L64
In quick summary it does the following:
read the contents of the file (aka, _sendIntercept)
based on mime type read the file either via readAsText or readAsDataURL
save the file contents to the .contents property of the file
Stop the send
To intercept the sending of the request on the network but still maintain the rest of the workflow we will replace a function called submitRequest. In the Dropzone code this function is a one liner and what I did was replace it with my own one-liner:
this._finished(files,'locally resolved, refer to "contents" property');
https://github.com/lifegadget/ui-dropzone/blob/0.7.2/addon/mixins/xhr-intercept.js#L66-L70
Provide access to retrieved document
The last step is just to ensure that our localAcceptHandler is put in place of the accept routine that dropzone supplies:
https://github.com/lifegadget/ui-dropzone/blob/0.7.2/addon/components/drop-zone.js#L88-L95
using the FileReader() solution is working amazingly good for me:
Dropzone.autoDiscover = false;
var dz = new Dropzone("#demo-upload",{
autoProcessQueue:false,
url:'upload.php'
});
dz.on("drop",function drop(e) {
var files = [];
for (var i = 0; i < e.dataTransfer.files.length; i++) {
files[i] = e.dataTransfer.files[i];
}
var reader = new FileReader();
reader.onload = function(event) {
var line = event.target.result.split('\n');
for ( var i = 0; i < line.length; i++){
console.log(line);
}
};
reader.readAsText(files[files.length-1]);

request.object.id not returning in afterSave() in Cloud Code

Parse.Cloud.afterSave(function(request) {
var type = request.object.get("type");
switch (type) {
case 'inspiration':
var query = new Parse.Query("Inspiration");
break;
case 'event':
var query = new Parse.Query("Event");
break;
case 'idea':
var query = new Parse.Query("Idea");
break;
case 'comment':
break;
default:
return;
}
if (query) {
query.equalTo("shares", request.object.id);
query.first({
success: function(result) {
result.increment("sharesCount");
result.save();
},
error: function(error) {
throw "Could not save share count: " + error.message;
}
});
}
});
For some reason request.object.id is not returning the object id from the newly created record. I've tested this code out throughly and have isolated it down to the request.object.id variable. I've even successfully ran it with using a pre-existing object ID and it worked fine. Am I using the wrong variable for the object ID?
Thanks in advanced for any help!
Had this exact problem a few weeks ago.
It turned out to be a bug in Parse's newest Javascript SDK. Please have a look at your CloudCode folder - it should contain a global.json file where you can specify the JavaScript SDK version. By default, it states "latest", change it to "1.4.2" and upload your CloudCode folder again.
In case the global.json file is missing in your cloud code folder, please have a look at this thread, where I described how to create it manually.
Thanks for the reply. I found out another work around for this for version 1.6.5. I should probably also mention that my use case for this code is to increment a count column (comments count) when a new relation has been added to a particular record (post).
Instead of implementing an afterSave method on my relation class (comment), I instead implemented a beforeSave method on my class (Post) and used request.object.dirtyKeys() to get my modified columns. From there I check to see if my dirty key was comments and if it is I increment my count column. It works pretty well actually.

Fineupload on.complete recover id, name and execute a PHP

I'm very interested getting the path and name of the file uploaded, and if the upload is a success, execute a php using the name and path of the uploaded file.
I just checked that on.complete could be useful, but if someone has an example would be just great.
.on('complete', function (event, id, filename, responseJSON) {
uploadedFileCounter++;
if (filesToUpload == uploadedFileCounter)
{
$(':input[type=button],:input[type=submit],:input[type=reset]').removeAttr('disabled');
//$("#overlay").fadeOut();
$("#modal-box").fadeOut();
$("#modal-overlay").fadeOut();
}
I found this example on another thread, but I don't have any idea how could I get the path and name on a php to store in a database and launch a new process with the uploded files.
So here is an example of how to do some of these tasks in plain ol' PHP. Would not recommend for production!
To get the filename in PHP:
function getName(){
// First we check if the user has provided an edited version of the filename.
// see: http://docs.fineuploader.com/branch/master/features/filename-edit.html
if (isset($_REQUEST['qqfilename']))
return $_REQUEST['qqfilename'];
// Otherwise we return whatever the browser/fine-uploader has named the file.
// see: http://docs.fineuploader.com/endpoint_handlers/traditional.html
if (isset($_FILES[$this->inputName]))
return $_FILES['qqfile']['name'];
}
To get the UUID in PHP:
// see: http://docs.fineuploader.com/endpoint_handlers/traditional.html
$uuid = $_REQUEST['qquuid'];
One method of creating a path on disk is to use the uuid in combination with the filename like so:
$path = join(DIRECTORY_SEPARATOR, array($uuid, get_name()));
At this point you can do whatever you want with the path, uuid, filename, or other data from fine-uploader (e.g., save the data in a database, ...)
If there is some reason fine-uploader needs to know the path, then you can return it in the response and use it in the onComplete handler:
.on('complete', function (event, id, filename, responseJSON) {
var path = responseJSON.path;
// do something ...
}

can't seem to get progress events from node-formidable to send to the correct client over socket.io

So I'm building a multipart form uploader over ajax on node.js, and sending progress events back to the client over socket.io to show the status of their upload. Everything works just fine until I have multiple clients trying to upload at the same time. Originally what would happen is while one upload is going, when a second one starts up it begins receiving progress events from both of the forms being parsed. The original form does not get affected and it only receives progress updates for itself. I tried creating a new formidable form object and storing it in an array along with the socket's session id to try to fix this, but now the first form stops receiving events while the second form gets processed. Here is my server code:
var http = require('http'),
formidable = require('formidable'),
fs = require('fs'),
io = require('socket.io'),
mime = require('mime'),
forms = {};
var server = http.createServer(function (req, res) {
if (req.url.split("?")[0] == "/upload") {
console.log("hit upload");
if (req.method.toLowerCase() === 'post') {
socket_id = req.url.split("sid=")[1];
forms[socket_id] = new formidable.IncomingForm();
form = forms[socket_id];
form.addListener('progress', function (bytesReceived, bytesExpected) {
progress = (bytesReceived / bytesExpected * 100).toFixed(0);
socket.sockets.socket(socket_id).send(progress);
});
form.parse(req, function (err, fields, files) {
file_name = escape(files.upload.name);
fs.writeFile(file_name, files.upload, 'utf8', function (err) {
if (err) throw err;
console.log(file_name);
})
});
}
}
});
var socket = io.listen(server);
server.listen(8000);
If anyone could be any help on this I would greatly appreciate it. I've been banging my head against my desk for a few days trying to figure this one out, and would really just like to get this solved so that I can move on. Thank you so much in advance!
Can you try putting console.log(socket_id);
after form = forms[socket_id]; and
after progress = (bytesReceived / bytesExpected * 100).toFixed(0);, please?
I get the feeling that you might have to wrap that socket_id in a closure, like this:
form.addListener(
'progress',
(function(socket_id) {
return function (bytesReceived, bytesExpected) {
progress = (bytesReceived / bytesExpected * 100).toFixed(0);
socket.sockets.socket(socket_id).send(progress);
};
})(socket_id)
);
The problem is that you aren't declaring socket_id and form with var, so they're actually global.socket_id and global.form rather than local variables of your request handler. Consequently, separate requests step over each other since the callbacks are referring to the globals rather than being proper closures.
rdrey's solution works because it bypasses that problem (though only for socket_id; if you were to change the code in such a way that one of the callbacks referenced form you'd get in trouble). Normally you only need to use his technique if the variable in question is something that changes in the course of executing the outer function (e.g. if you're creating closures within a loop).

capture a pages xmlhttp requests with a userscript

I have a user script (for chrome and FF) that adds significant functionality to a page, but has recently been broken because the developers added some AJAX to the page. I would like to modify the script to listen to the pages xmlhttp requests, so that I can update my added content dynamically, based on the JSON formatted responseText that the page is receiving.
A search has turned up many functions that SHOULD work, and do work when run in the console. However they do nothing from the context of a user script.
(function(open) {
XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
this.addEventListener("readystatechange", function() {
console.log(this.readyState);
}, false);
open.call(this, method, url, async, user, pass);
};
})(XMLHttpRequest.prototype.open);
From: How can I intercept XMLHttpRequests from a Greasemonkey script?
This works perfectly in the console, I can change this.readyState to this.responseText and it works great (though in the script I will need it to turn the JSON data into an object, and then let me manipulate it within the userscript. Not just write to the console). However if I paste it into a userscript nothing happens. The xmlhttp requests on the page do not seem to be detected by the event handler in the userscript.
The page doing the requesting is using the jquery $.get() function, if that could have anything to do with it. Though I don't think it does.
I can't imagine that there isn't a way, seems like any userscript running on an AJAX page would want this ability.
Since the page uses $.get(), it's even easier to intercept requests. Use ajaxSuccess().
This will work in a Greasemonkey(Firefox) script:
Snippet 1:
unsafeWindow.$('body').ajaxSuccess (
function (event, requestData)
{
console.log (requestData.responseText);
}
);
Assuming the page uses jQuery in the normal way ($ is defined, etc.).
This should work in a Chrome userscript (as well as Greasemonkey):
Snippet 2:
function interceptAjax () {
$('body').ajaxSuccess (
function (event, requestData)
{
console.log (requestData.responseText);
}
);
}
function addJS_Node (text, s_URL, funcToRun) {
var D = document;
var scriptNode = D.createElement ('script');
scriptNode.type = "text/javascript";
if (text) scriptNode.textContent = text;
if (s_URL) scriptNode.src = s_URL;
if (funcToRun) scriptNode.textContent = '(' + funcToRun.toString() + ')()';
var targ = D.getElementsByTagName('head')[0] || D.body || D.documentElement;
targ.appendChild (scriptNode);
}
addJS_Node (null, null, interceptAjax);
Re:
"But how then do I get that data to the script? ... (So I can) use the data later in the script."
This works in Greasemonkey(Firefox); it might also work in Chrome's Tampermonkey:
Snippet 3:
function myAjaxHandler (requestData) {
console.log ('myAjaxHandler: ', requestData.responseText);
}
unsafeWindow.$('body').ajaxSuccess (
function (event, requestData) {
myAjaxHandler (requestData);
}
);
But, if it doesn't then you cannot share JS information (easily) between a Chrome userscript and the target page -- by design.
Typically what you do is inject your entire userscript, so that everything runs in the page scope. Like so:
Snippet 4:
function scriptWrapper () {
//--- Intercept Ajax
$('body').ajaxSuccess (
function (event, requestData) {
doStuffWithAjax (requestData);
}
);
function doStuffWithAjax (requestData) {
console.log ('doStuffWithAjax: ', requestData.responseText);
}
//--- DO YOUR OTHER STUFF HERE.
console.log ('Doing stuff outside Ajax.');
}
function addJS_Node (text, s_URL, funcToRun) {
var D = document;
var scriptNode = D.createElement ('script');
scriptNode.type = "text/javascript";
if (text) scriptNode.textContent = text;
if (s_URL) scriptNode.src = s_URL;
if (funcToRun) scriptNode.textContent = '(' + funcToRun.toString() + ')()';
var targ = D.getElementsByTagName('head')[0] || D.body || D.documentElement;
targ.appendChild (scriptNode);
}
addJS_Node (null, null, scriptWrapper);

Resources