Get files selected queue valums fileupload.js - javascript

I need to know how to get the files selected queue once the user has selected the files from computer and clicks on, because I want to show a message as "Uploaded files 1/200", but I don't know how to get the total of the files selected.
I just know I have these methods (onSubmit, onProgress, onComplete, onError) but none works for me:
// url of the server-side upload script, should be on the same domain
action: '/server/upload',
// additional data to send, name-value pairs
params: {},
// validation
// ex. ['jpg', 'jpeg', 'png', 'gif'] or []
allowedExtensions: [],
// each file size limit in bytes
// this option isn't supported in all browsers
sizeLimit: 0, // max size
minSizeLimit: 0, // min size
abortOnFailure: true, // Fail all files if one doesn't meet the criteria
// set to true to output server response to console
debug: false,
// events
// you can return false to abort submit
onSubmit: function(id, fileName){},
onProgress: function(id, fileName, loaded, total){},
onComplete: function(id, fileName, responseJSON){},
onCancel: function(id, fileName){},
onError: function(id, fileName, xhr){}
messages: {
// error messages, see qq.FileUploaderBasic for content
},
showMessage: function(message){ alert(message); }

I know how to get the files selected.
In onSubmit function make window.event.target.files:
onSubmitPDF: function( id, fileName ){
console.log(window.event.target.files);
}
window.event.target.files gives you the information of the current files selected queue.

Related

Memory buffers fills up when I stream upload a file, though passing a disk storage location param

Trying to stream-upload to S3 using skipper and skipper-s3 using this code
image_upload : function (req,res) {
// depends on bodyparser:skipper in confing/http.js
console.log("Uploading image .. ");
req.file('image')
.upload({
adapter: require('skipper-s3'),
key: KEY,
secret: SECRET,
bucket: 'mybucket',
tmpdir: 'tmp/s3-multiparts'
}, function whenDone(err, uploadedFiles) {
if (err){
return res.negotiate(err);
} else {
dict = {
files: uploadedFiles,
textParams: req.params.all()
}
return res.ok(dict);
}
}
);
};
I have 2 problems:
First: when I try to upload some file, I can see that this file buffers in memory, instead just buffering to the disk (path added to options).
Actually this is a big problem, as my memory will fill up so quickly when having many users concurrently uploading
Second: my application crashes when upload is bigger than 5MBs, giving me this error
events.js:85
throw er; // Unhandled 'error' event
^
Error: Request aborted
at IncomingMessage.onReqAborted (~Desktop/myApp/node_modules/sails/node_modules/skipper/node_modules/multiparty/index.js:175:17)
at IncomingMessage.emit (events.js:104:17)
at abortIncoming (_http_server.js:279:11)
at Socket.serverSocketCloseListener (_http_server.js:292:5)
at Socket.emit (events.js:129:20)
at TCP.close (net.js:485:12)
Solution to your second problem:
You can specify maximum size of file to be uploaded. Default is 5 MB.
req.file('some_file').upload({
dirname: 'path to store the file',/* optional. defaults to assets/uploads I guess*/
saveAs: 'new file name', /* optional. default file name */
maxBytes: 5 * 1024 * 1024 //5 MB
}, function(err, uploadedFiles) {
});
I am not sure about the first problem though. You don't need to specify a tempdir in options. Skipper-S3 by default writes the file to <your project root>/.tmp/s3-upload-part-queue for its upload purpose. I don't see why the memory should get filled up. Can you possibly remove the tempdir and check?

setDeleteFileParams doesnt seem to work

I am using 5.3.2 in basic mode as I need control over the UI.
I have added code to allow the uploads and then created little UI elements that can then trigger a deletion. I need to know the filename when I am deleting. So I used setDeleteFileParams but nothing is attached to the request.
var uploader = new qq.FineUploaderBasic({
button: document.getElementById('btnUploadFiles'),
debug: true,
autoUpload: true,
request: {
paramsInBody: true,
endpoint: '../myendpoint.htm',
params: {
tempID: 'myidwhatever'
}
},
deleteFile: {
enabled: true,
forceConfirm: false,
method: 'POST',
endpoint: '../myendpoint.htm'
},
callbacks: {
onSubmitted: function(id, name){
//do work
},
onDelete: function(id) {
this.setDeleteFileParams({filename: this.getName(id)}, id);
},
onDeleteComplete: function(UID, xhr, isError){
//remove my UI element
},
onComplete: function(UID, name, responseJSON, xhr) {
//create an element and stick it in
}
}
})
//ADD THE DELETE BUTTON ACTIONS
$('uploadedFiles').addEvent("click:relay(.deleteMyFile)", function(event, element) {
event.preventDefault();
arr = element.id.split('_')
uploader.deleteFile(arr[1]);
});
Im using Mootools as my JS framework. Everything triggers ok and the console logs out the filename correctly when I delete a file but when I look at the request there is no 'filename' parameter.
Thanks for any help.
By the time your onDeleteFile callback has been called, the file is already setup to be deleted. If you'd like to influence (or prevent) the underlying request, you'll need to put your logic inside of a onSubmitDelete callback handler instead.
For example:
callbacks: {
onSubmitDelete: function(id) {
console.log(this.getName(id));
this.setDeleteFileParams({filename: this.getName(id)}, id);
}
}

Dropzone.js v4+ - Display existing files on server with work limiting the number of files and other functions

How to add existing files on server to dropzone with right work all functions and right styling?
I wrote a function to add files: addCustomFile(file, thumbnail_url , responce)
Powered by Version: 4.0.1 stable
Correct working: maxFiles limit, event maxfilesexceeded, event success and others
$("#dropzone-images").dropzone({
url: "...",
paramName: 'image_temp',
maxFiles: 1,
init: function () {
this.addCustomFile = function(file, thumbnail_url , responce){
// Push file to collection
this.files.push(file);
// Emulate event to create interface
this.emit("addedfile", file);
// Add thumbnail url
this.emit("thumbnail", file, thumbnail_url);
// Add status processing to file
this.emit("processing", file);
// Add status success to file AND RUN EVENT success from responce
this.emit("success", file, responce , false);
// Add status complete to file
this.emit("complete", file);
}
this.addCustomFile(
// File options
{
// flag: processing is complete
processing: true,
// flag: file is accepted (for limiting maxFiles)
accepted: true,
// name of file on page
name: "The name",
// image size
size: 12345,
// image type
type: 'image/jpeg',
// flag: status upload
status: Dropzone.SUCCESS
},
// Thumbnail url
"http://.../img.jpg",
// Custom responce for event success
{
status: "success"
}
);
}
});

Jquery : Post Request is breaking while uploading multiple images

I am using Plupload js plugin to upload multiple images in one request. This plugin is working like if someone adding 5 images at a time then post request will go 5 times to upload each of images separately. As we know Post request require unique csrf token but in my case due to same token after one time, post request is failing.
Here is my code ...
<c:set var="csrfTokenVal"><csrf:token-value uri="<%=request.getRequestURI()%>"/></c:set>
<script>
var csrftokenV="${csrfTokenVal}";
$("#uploader").plupload({
// General settings
runtimes : 'html5,flash,silverlight,html4',
url:'/view/SurgeryNotesComponentController?uploadSurgeryImage=true&'+csrftokenN+'='+csrftokenV,
// User can upload no more then 20 files in one go (sets multiple_queues to false)
max_file_count: 10,
chunk_size: '1mb',
// Resize images on clientside if we can
resize : {
width : 600,
height : 610,
quality : 90,
//crop: true // crop to exact dimensions
},
filters : {
// Maximum file size
max_file_size : '1mb',
// Specify what files to browse for
mime_types: [
{title : "Image files", extensions : "jpg,gif,png"},
{title : "Zip files", extensions : "zip"}
]
},
// Rename files by clicking on their titles
rename: true,
// Sort files
sortable: true,
// Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
dragdrop: true,
// Views to activate
views: {
list: true,
thumbs: false, // Show thumbs
active: 'thumbs'
},
init: {
FilesAdded: function(up, files) {
$("#uploader_filelist").show();
},
FileUploaded: function(up, file, info, res) {
var imageObjectArray=$.parseJSON(info.response);
for(i=0;i<imageObjectArray.objectList.length; i++){
$('#showfilelist ul').append("<li><a class='delIcon-image' href='#delete' id='delSurgeryImageIcon'></a><a id=" + imageObjectArray.objectList[i].uid + " class='cboxElement imguid' href='${contextPath}/view/SurgeryNotesComponentController?surgeryImage=true&"+csrftokenN+ "="+ csrftokenV+"&attachmentLocation="+imageObjectArray.objectList[i].attachmentLocation+"' target='_blank'><img src='${contextPath}/view/SurgeryNotesComponentController?surgeryImage=true&"+csrftokenN+ "="+ csrftokenV+"&attachmentLocation="+imageObjectArray.objectList[i].attachmentLocation+"' border='0'>"+"</a> <strong>"+noteAddedMsg+"</strong><span class='image-created'>"+imageObjectArray.objectList[i].formattedDate+" "+byMsg+" "+imageObjectArray.objectList[i].userName+" </span></li>");
}
$("#uploader_filelist").empty().hide();
_SPINE.colorboxOverlay.coloboxPopup();
_SPINE.surgeryNotes.deleteImages();
$(".plupload_done .plupload_file_thumb").removeClass("hide")
},
ChunkUploaded: function (up, file, response) {
response = $.parseJSON(response.response || "null");
if (response.chunk == 3) {
up.stop();
up.start();
}
console.log(file.loaded);
}
},
// Flash settings
flash_swf_url : '${siteAssetsUrl}/assets/spine/js/external/Moxie.swf',
// Silverlight settings../assets/js
silverlight_xap_url : '${siteAssetsUrl}/assets/spine/js/external/Moxie.xap'
});
</script>
Here you can see I am generating scrf token (csrftokenV) and sending it in url to make it post supported.
Now the problem is if I am uploading more than 1 images (lets say 3), then 3 time post request will go. Each time i will get same csrf token and after uploaing first image, furthure images will not work and i will get this exception ....
WARNING: potential cross-site request forgery (CSRF) attack thwarted (user:<anonymous>, ip:127.0.0.1, uri:/**/image, error:request token does not match session token)
Please help me to solve this problem. Thanks
Finally One of my friend had solved the issue. It can't be possible to handle this issue through client side script so we leverage the power of Java. We had updated the csrfToken based on new request and sent it out with response.
Here is a solution ..
private String updateToken(HttpServletRequest request)
{
final HttpSession session = request.getSession(false);
CsrfGuard csrfGuard = CsrfGuard.getInstance();
csrfGuard.updateTokens(request);
String newToken=(String) session.getAttribute(REQUEST_TOKEN);
return newToken;
}
Setting newToken in response ...
response.setResult(this.updateToken(request));
return response;
Now we can change the url in beforeUpload event and set new token in the url.
BeforeUpload: function(up, file)
{
up.settings.url='/view/SurgeryNotesComponentController?uploadSurgeryImage=true&'+csrftokenN+'='+tokenRefresh
}
FileUploaded: function(up, file, info, res)
{
var imageObjectArray=$.parseJSON(info.response);
tokenRefresh=imageObjectArray.result;
}

Valums file uploader plugin shows upload failed message each time

I am using valum file uploader. The js code for initializing plugin is:
function Initializer() {
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '/_Image/Upload',
params: {},
allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
debug: true,
onSubmit: function (id, fileName) { },
onProgress: function (id, fileName, loaded, total) { },
onComplete: function (id, fileName, responseJSON) { },
onCancel: function (id, fileName) { },
onError: function (id, fileName, xhr) { },
messages: {
typeError: "{file} has invalid extension. Only {extensions} are allowed.",
sizeError: "{file} is too large, maximum file size is {sizeLimit}.",
minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
emptyError: "{file} is empty, please select files again without it.",
allowedExtensionsError : "{file} is not allowed.",
onLeave: "The files are being uploaded, if you leave now the upload will be cancelled."
},
showMessage: function (message) {
alert(message);
}
});
}
The file is successfully uploaded on the server but the plugin is showing the file uplode fail message each time.
What's the issue?
You are most likely not returning valid JSON as your server response. The readme clearly states, in many places, that this is required. Please have a look at the readme.

Categories