correct implementation of plupdate - javascript

i´m implementing this upload library, maybe not much people use this, but maybe somebody can help me to figure how to solve this.
So i'm already uploading, the thing is that i want to implement the "uploader" objet, like
upload.bind();
i would like to know if anybody here can provide me links or maybe clear my idea.
thank you so much.
This is my code:
uploader = $("#uploader").plupload({
// General settings
runtimes: 'html5,flash,silverlight,html4',
url: objMaterial.geturl(),
urlstream_upload: true, //cambiar url en tiempo real
multi_selection: multiSelection,
unique_names: unicoNombre,
// User can upload no more then 20 files in one go (sets multiple_queues to false)
max_file_count: 1,
chunk_size: '1mb',
// Resize images on clientside if we can
filters: {
// Maximum file size
max_file_size: '50mb',
// Specify what files to browse for
mime_types: [
{
title: titulo,
extensions: extensiones
}
]
},
// 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: true, // Show thumbs
active: 'thumbs'
},
// Flash settings
flash_swf_url: '../../js/Moxie.swf',
// Silverlight settings
silverlight_xap_url: '../../js/Moxie.xap'
});
//uploader = $("#uploader").plupload();
uploader = $('#uploader').plupload();
console.log(uploader);
//uploader = $("#flash_uploader").pluploadQueue();
uploader.bind('QueueChanged', function (up, files)
{
files_remaining = uploader.files.length;
});

i want to answer this question, i found a solution.
so all these objects are events.
here you have a complete example of how to implement them.
uploader = $("#uploader").plupload({
// General settings
runtimes: 'html5,html4',
url: objMaterial.geturl(),
// Maximum file size
max_file_size: '50mb',
chunk_size: '1mb',
max_file_count: 1,
// Resize images on clientside if we can
resize: {
width: 200,
height: 200,
quality: 90,
crop: true // crop to exact dimensions
},
// Specify what files to browse for
filters: [
{title: "PDF", extensions: "PDF"}
],
// 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: true, // Show thumbs
active: 'thumbs'
},
// Post init events, bound after the internal events
init: {
PostInit: function () {
// Called after initialization is finished and internal event handlers bound
log('[PostInit]');
document.getElementById('uploadfiles').onclick = function () {
uploader.start();
return false;
};
},
Browse: function (up) {
                // Called when file picker is clicked                
            },
            Refresh: function (up) {
                // Called when the position or dimensions of the picker change                 
            }, 
            StateChanged: function (up) {
                // Called when the state of the queue is changed                 
            }, 
            QueueChanged: function (up) {
                // Called when queue is changed by adding or removing files                 
            },
OptionChanged: function (up, name, value, oldValue) {
// Called when one of the configuration options is changed
},
BeforeUpload: function (up, file) {
// Called right before the upload for a given file starts, can be used to cancel it if required
},
            UploadProgress: function (up, file) {
                // Called while file is being uploaded                 
            },
FileFiltered: function (up, file) {
// Called when file successfully files all the filters                 
},
            FilesAdded: function (up, files) {
                // Called when files are added to queue                
                plupload.each(files, function (file) {                     
                });
            },
            FilesRemoved: function (up, files) {
                // Called when files are removed from queue                 
                plupload.each(files, function (file) {                     
                });
            }, 
            FileUploaded: function (up, file, info) {
                // Called when file has finished uploading
jQueryMessage('El archivo se ha enviado exitosamente!', 1);                 
            }, 
            ChunkUploaded: function (up, file, info) {
                // Called when file chunk has finished uploading                 
            },
UploadComplete: function (up, files) {
// Called when all files are either uploaded or failed                 
},
Destroy: function (up) {
// Called when uploader is destroyed                 
},
            Error: function (up, args) {
                // Called when error occurs                 
            }
    },
// Flash settings
flash_swf_url: '/plupload/js/Moxie.swf',
// Silverlight settings
silverlight_xap_url: '/plupload/js/Moxie.xap'
});
i hope this can help you

Related

how can i enqueue a file manually in dropzone/ vue dropzone 2

I am working on uploading functionality for a product i'm building with vuedropzone 2, from the dropzone docs http://www.dropzonejs.com/#config-autoQueue , it is possible to prevent the accepted/added files from being queued automatically by setting autoQueue to false, also it is stated there that the files can be queued manually by calling enqueueFile(file) manually.
Setting autoQueue to false works, however when i try to add the file manually to the queue, its not working and i am getting this error this.$refs.dropzone.enqueueFile is not a function
my script:
new Vue({
data: {
dropzoneOptions: {
url: 'https://httpbin.org/post',
thumbnailWidth: 150,
maxFilesize: 1000,
addRemoveLinks: true,
autoProcessQueue: false,
autoQueue: false,
dictDefaultMessage: "<i class='is-size-150 fa fa-cloud-upload'>
</i>",
headers: {
'Access-Control-Allow-Origin': '*',
},
parallelUploads: 1,
},
},
methods: {
upload() {
document.querySelector('.dropzone').click();
},
startUpload() {
this.$refs.dropzone.getAcceptedFiles().forEach(f => this.$refs.dropzone.enqueueFile(f));
....
},
})
my template:
div
button.button.is-primary(#click="upload") upload Document(s)
dropzone(
v-show="false",
:id="id",
ref="dropzone",
:maxNumberOfFiles="100" ,
:maxFileSizeInMB="1000",
:options="dropzoneOptions",
#vdropzone-upload-progress="updateFilename",
#vdropzone-files-added="handleFilesAdded",
#vdropzone-error="handleUploadError",
#vdropzone-total-upload-progress="progress",
#vdropzone-queuecomplete="handleUploadComplete",
#vdropzone-success="fileUploaded",
:parallelUploads="1",
)
// this dialog modal shows only when files have been selected after clicking upload document button
el-dialog(title="Upload Files", :visible.sync="hasAddedFiles")
div(slot="title")
// button for adding more files before clicking start upload
button.is-info.button.ml-15(#click="addFiles") Add File(s)
// table that lists all selected files
el-table(:data="addedFiles", :height="400")
el-table-column(type="index" :index="1")
el-table-column(
property="name",
show-overflow-tooltip,
label="Name",
min-width="200"
)
el-table-column(property="type" label="File type")
el-table-column(label="Delete" width="100")
template(scope="props")
// button for removing a file
button.button.trash(
:class="$style.trash",
#click="removeFile(props.row)",
)
i.material-icons delete
div(slot="footer")
// select file type
el-select(
v-model="addedFilesType"
filterable
allow-create
placeholder="Choose file(s) type"
)
el-option(
v-for="(item, index) in documentTypes"
:key="index"
:value="item"
)
// button for enqeueing and start processing the queue in order to start files upload
button.button.is-primary.is-medium.ml-15(
#click="startUpload",
:disabled="!addedFilesType.length",
)
span.icon
i.material-icons cloud_upload
span Start Upload
The enqueueFile is not delegated on the vue-dropzone component. So it's not available on this.$refs.dropzone.
But there is a solution to this (however not very elegant). You should be able to call this.$refs.dropzone.dropzone to get the underlying dropzone object.
So this.$refs.dropzone.dropzone.enqueueFile(f) should work.

how to run a background service in electron js?

How to implement background service using electron.
i'm having a trouble can anyone tell me how to start a background
service using electron which runs even after closing the app. i have
tried many solutions but all of them stop the service after closing
the app.
You can use tray. here is an example (source):
"use strict";
// [run the app]
// $ npm install electron
// $ ./node_modules/.bin/electron .
const {app, nativeImage, Tray, Menu, BrowserWindow} = require("electron");
let top = {}; // prevent gc to keep windows
app.once("ready", ev => {
top.win = new BrowserWindow({
width: 800, height: 600, center: true, minimizable: false, show: false,
webPreferences: {
nodeIntegration: false,
webSecurity: true,
sandbox: true,
},
});
top.win.loadURL("https://google.com/");
top.win.on("close", ev => {
//console.log(ev);
ev.sender.hide();
ev.preventDefault(); // prevent quit process
});
// empty image as transparent icon: it can click
// see: https://electron.atom.io/docs/api/tray/
top.tray = new Tray(nativeImage.createEmpty());
const menu = Menu.buildFromTemplate([
{label: "Actions", submenu: [
{label: "Open Google", click: (item, window, event) => {
//console.log(item, event);
top.win.show();
}},
]},
{type: "separator"},
{role: "quit"}, // "role": system prepared action menu
]);
top.tray.setToolTip("hello electrol");
//top.tray.setTitle("Tray Example"); // macOS only
top.tray.setContextMenu(menu);
// Option: some animated web site to tray icon image
// see: https://electron.atom.io/docs/tutorial/offscreen-rendering/
top.icons = new BrowserWindow({
show: false, webPreferences: {offscreen: true}});
top.icons.loadURL("https://trends.google.com/trends/hottrends/visualize");
top.icons.webContents.on("paint", (event, dirty, image) => {
if (top.tray) top.tray.setImage(image.resize({width: 16, height: 16}));
});
});
app.on("before-quit", ev => {
// BrowserWindow "close" event spawn after quit operation,
// it requires to clean up listeners for "close" event
top.win.removeAllListeners("close");
// release windows
top = null;
});
Yes, it is possible by using electron-process npm library.
ref :- https://www.npmjs.com/package/electron-process
First you will have to register the module which you want to run in background, just create simple background.html,
--background.html--
add below lines in script tag,
const background = require('electron-process').background;
background.registerModule(require('../main/snippets/SnippetsManager'));
In main process just create one browser window in which your background.html will run and keep it as hidden window,
--main.js--
app.once("ready", ev => {
service = new BrowserWindow({
width: 80, height: 60, center: true, minimizable: false, show: false,
webPreferences: {
nodeIntegration: false,
webSecurity: true,
sandbox: true,
},
});
service.loadURL("file://' + __dirname + '/background.html");
service.on("close", ev => {
ev.sender.hide();
ev.preventDefault(); // prevent quit process
});
});
Hope it helped,
Regards.
Electron is not designed to run in background. If you are closing
application then it will terminate all processes related with it.
Electron is only used to provide GUI layer. After all it is hybrid application and it doesn't interact with core OS services to live
itself like background service.
Apart from this there are two options:
If you write a service with something else, say a node or .net application, then you probably could use Electron to interact with that service (via bundled Node accessing Windows APIs).
Create feature like system tray. Minimise application to system tray.
Ref Link

Can't display validation errors with kartik-v bootstrap file input plugin

I've opened an issue on the github plugin, but it doesn't seem to be very active, so I asked here too.
I'm sending my files through ajax but when the upload fails (as with height too small) I don't get the real error message, but I get an error from my ajax url, but this one makes no sense since nothing is sent.
I think the ajax route shouldn't be called, but anyway, I tried to play with 'fileuploaderror' and I do get the wanted errors, but I don't know how to display them. There must be a simple way in the fileuploaderror event, but I don't know it.
Can anyone help me with this one ?
Issue link |
Plugin page
Thanks
$("#id").fileinput({
uploadUrl: "/ajax/snippet/image/send/78", // server upload action
deleteUrl: "/ajax/snippet/image/remove/",
uploadAsync: false,
showUpload: false, // hide upload button
showRemove: false, // hide remove button
maxFileCount: maxFile,
browseOnZoneClick: true,
language: "fr",
minImageWidth: 150,
minImageHeight: 150,
allowedFileExtensions: ["jpg", "jpeg", "gif", "bmp", "png"],
multiple: true,
maxFileSize: 5000,
uploadExtraData: function (previewId, index) {
return {key: index};
},
initialPreviewAsData: true,
overwriteInitial: false,
}).on("filebatchselected", function (event, files) {
// trigger upload method immediately after files are selected
$(this).fileinput("upload");
}).on('fileuploaderror', function (event, data, msg) {
var form = data.form, files = data.files, extra = data.extra,
response = data.response, reader = data.reader;
// get message
alert(msg);
});
}
Ok, I got the answer, in my "filebatchselected" event, I was forcing the upload.
I need to check if I have valid files to upload first.
$("#id").fileinput({
uploadUrl: "/ajax/snippet/image/send/78", // server upload action
deleteUrl: "/ajax/snippet/image/remove/",
uploadAsync: false,
showUpload: false, // hide upload button
showRemove: false, // hide remove button
maxFileCount: maxFile,
browseOnZoneClick: true,
language: "fr",
minImageWidth: 150,
minImageHeight: 150,
allowedFileExtensions: ["jpg", "jpeg", "gif", "bmp", "png"],
multiple: true,
maxFileSize: 5000,
uploadExtraData: function (previewId, index) {
return {key: index};
},
initialPreviewAsData: true,
overwriteInitial: false,
}).on("filebatchselected", function (event, files) {
// trigger upload method immediately after files are selected
var filesStack = $('#input-id').fileinput('getFileStack');
if (filesStack.length > 0) {
$(this).fileinput("upload");
}
});
}

When is "is_initial" true in Dygraph's drawCallback?

I have a Dygraphs chart that works perfectly when I provide a file URL for a data source. When I embedded the data directly into the HTML wrapper, however, the functions in my drawCallback don't fire. Tracing with Firebug, I find that is_initial is True when I load the page with the URL reference, but False when I embed the data (and labels) in native format, even if I place onLoad="drawCallback(vGraph,True);" within the <body> tag. I've "solved" this by setting my own variable to test for first-time execution.
Here's the original, functional, code for an external data source:
var vGraph = new Dygraph(document.getElementById("dgraphChartContainer"),
ExternalDataSource.csv,
{ //options
connectSeparatedPoints: true,
labelsDiv: "dygraphLabelsContainer",
...
}
);
vGraph.updateOptions({
highlightCallback: function(event, xdate, points_array, rowNumber, seriesName) {
...
},
unhighlightCallback: function(event) {
...
},
drawCallback: function(g, is_initial) {
if (!is_initial) return;
buildTagList(vGraph.getLabels());
mySeriesColors = vGraph.getColors();
buildStyleDefinitions();
}
});
As I said, this works great, even with the blind g parameter in the drawCallback.
This is the work-around I developed for the scenario when I embed the data source.
var vFirstTime = true;
var vGraph = new Dygraph(document.getElementById("dgraphChartContainer"),
[
[ new Date("2011/10/15 00:04:55"),null,null,-9.2,null,null,null,null,null,null],
[ new Date("2011/10/24 10:39:32"),null,null,null,null,null,-9.2,null,null,null],
...
[ new Date("2011/10/25 21:02:30"),null,null,null,null,null,null,null,20.3,null],
[ new Date("2013/10/28 08:49:52"),null,null,-17.9,null,null,null,null,null,null]
],
{ //options
labels: ["Event_Date","code-32565","code-32566","code-32568","code-32569","code-32573","code-32574","code-32575","code-32577","code-32578"],
connectSeparatedPoints: true,
labelsDiv: "dygraphLabelsContainer",
...
}
);
vGraph.updateOptions({
highlightCallback: function(event, xdate, points_array, rowNumber, seriesName) {
...
},
unhighlightCallback: function(event) {
...
},
// drawCallback: function(g, is_initial) {
// if (!is_initial) return;
drawCallback: function() {
if (!vFirstTime) return;
buildTagList(vGraph.getLabels());
mySeriesColors = vGraph.getColors();
buildStyleDefinitions();
vFirstTime=false;
}
});
Is there something I can do to use is_initial in my drawCallback call regardless of the data source?
Your first example will work if you move your callbacks into the constructor:
var vGraph = new Dygraph(document.getElementById("dgraphChartContainer"),
ExternalDataSource.csv,
{ //options
connectSeparatedPoints: true,
labelsDiv: "dygraphLabelsContainer",
highlightCallback: function(event, xdate, points_array, rowNumber, seriesName) {
...
},
unhighlightCallback: function(event) {
...
},
drawCallback: function(g, is_initial) {
if (!is_initial) return;
buildTagList(vGraph.getLabels());
mySeriesColors = vGraph.getColors();
buildStyleDefinitions();
},
...
});
So, what's going on here?
The drawCallback gets fired with is_initial = true when the chart draws for the first time. In your original code, this happens after the XMLHttpRequest for the data comes back.
The order of operations is:
constructor
updateOptions
drawCallback(is_initial=true)
When you inline your data, dygraphs doesn't need to wait for the XHR to come back. Now, the order of operations is:
constructor
drawCallback(is_initial=true)
updateOptions
drawCallback(is_initial=false)
The second drawCallback happens because you called updateOptions(). So drawCallback is getting fired with is_initial = true, it's just that you're not listening for it early enough.
dygraphs provides a .ready() method to let you avoid all this intricacy. You may be happier using it instead:
var vGraph = new Dygraph( ... );
vGraph.ready(function() {
buildTagList(vGraph.getLabels());
mySeriesColors = vGraph.getColors();
buildStyleDefinitions();
});

TIBlob passed through application-level event becomes NULL on the receiving end

I have a very simple app where the user selects an image from the iOS photo gallery.
The TIBlob passed to Titanium.Media.openPhotoGallery.success event is then passed to an application-level event.
The issue is that the TIBlob is NULL when the application level event is received.
Below is a complete code sample.
Titanium.UI.setBackgroundColor('#000');
var win = Ti.UI.createWindow({title: 'Camera Test', exitOnClose: true, fullscreen: true, backgroundColor: '#ffffff'});
var bt = Ti.UI.createButton({'title': 'Gallery', top: 10, width: 200, height: 50});
bt.addEventListener('click', function(e) {
Titanium.Media.openPhotoGallery({
success:function(event) {
if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO) {
alert(event.media);
Ti.App.fireEvent('uploadImage', {image: event.media, source: 'gallery'});
}else {
alert('Image was not uploaded because the type was invalid.');
}
},
cancel:function() {
},
error:function(err) {
alert('Error selecting image from gallery: ' + err);
Ti.API.error(err);
},
allowEditing: false,
autohide: true,
mediaTypes:[Ti.Media.MEDIA_TYPE_PHOTO]
});
});
Ti.App.addEventListener('uploadImage', function(e) {
alert(e.image);
alert(e.source);
});
win.add(bt);
win.open();
Any suggestions?
The Appcelerator Guides say that objects passed through and event must be JSON-serializable https://wiki.appcelerator.org/display/guides/Event+Handling#EventHandling-Firingevents. A TiBlob is not serializable, so I think the blog is not making it through the event.
If this really is a very simple app, I would suggest changing that to a function call instead of firing an event and the blob will be preserved. However, if this absolutely needs to be an event, you could pass event.media.nativePath instead and then read a blob out of that when you actually need to do something with it.

Categories

Resources