UIKIT 3 get the name of the file been uploaded - javascript

I try to create a function where the user uploads the file and then showing the image that's been uploaded to a div. But I need to have the name of the file in order to add the src attr to
Seems like UIKIT 3 does not have a way where I can get the name of the file when it's dropped or selected.
Anyone can help this, please?
Here's the code from UIKIT, and here's the docs they provide
UIkit.upload('.js-upload', {
url: '../config/forms.php',
beforeSend: function () {
console.log('beforeSend', arguments);
},
beforeAll: function () {
console.log('beforeAll', arguments);
},
load: function () {
console.log('load', arguments);
},
error: function () {
console.log('error', arguments);
},
complete: function () {
console.log('complete', arguments);
},
loadStart: function (e) {
console.log('loadStart', arguments);
bar.removeAttribute('hidden');
bar.max = e.total;
bar.value = e.loaded;
},
progress: function (e) {
console.log('progress', arguments);
bar.max = e.total;
bar.value = e.loaded;
},
loadEnd: function (e) {
console.log('loadEnd', arguments);
bar.max = e.total;
bar.value = e.loaded;
},
completeAll: function (arguments) {
console.log('completeAll', arguments);
setTimeout(function () {
bar.setAttribute('hidden', 'hidden');
}, 1000);
}
});

JS side:
UIkit.upload('.js-upload', {
url: 'file_upload.php',
multiple: false,
mime: "image/*",
completeAll: function () {
uploaded_filename = arguments[0].response;
}
});
PHP Side:
$uploads_dir = PUBLIC_FOLDER."uploads";
$tmp_name = $_FILES['form-drop-place']['tmp_name'];
$image_name = $_FILES['form-drop-place']['name'];
$ext = pathinfo($image_name, PATHINFO_EXTENSION);
$new_name = "newname." . $ext;
$new_place = $uploads_dir . "/" . $new_name;
if ( move_uploaded_file($tmp_name, $new_place) ) {
die($new_name);
} else {
die();
}

Related

Simulating drag drop with react testutils not working

I'm try to test my ReactJS mixin for drag and drop functionality using jasmine, karma and React TestUtils.
No exception is thrown but when debugging it seems that the function bound to the event listener not being executed when the event is simulated.
You can clone the it here:
https://github.com/itsh01/react-dragdrop/tree/testing-simutale-events
Thank you very much in advance.
Here is my test:
beforeEach(function () {
var CompDrag = React.createClass({
mixins: [DragDropMixin],
dragDrop: function dragDrop() {
return {
draggable: true,
dropType: 'test',
dataTransfer: {
test: true
}
};
},
render: function render() {
return React.createElement('div', {});
}
});
var CompDrop = React.createClass({
mixins: [DragDropMixin],
dragDrop: function dragDrop() {
var self = this;
return {
droppable: true,
acceptableTypes: ['test'],
drop: function (data) {
self.setState(data);
}
};
},
render: function render() {
return React.createElement('div', {});
}
});
elementDrag = React.createElement(CompDrag, {});
elementDrop = React.createElement(CompDrop, {});
});
...
it('should attach drop functionality when configured', function () {
var renderedDrag = TestUtils.renderIntoDocument(elementDrag);
var renderedDrop = TestUtils.renderIntoDocument(elementDrop);
var nodeDrag = renderedDrag.getDOMNode();
var nodeDrop = renderedDrop.getDOMNode();
var mockEvent = {
preventDefault: function () {},
dataTransfer: {
types: ["objtopass"],
setData: function () {},
getData: function () {
return JSON.parse({
dropType: 'test',
data: {
test: true
}
});
}
}
};
TestUtils.SimulateNative.dragStart(nodeDrag, mockEvent);
TestUtils.Simulate.dragOver(nodeDrop, mockEvent);
TestUtils.Simulate.drop(nodeDrop, mockEvent);
expect(renderedDrop.state).not.toBeNull();
});
Here is the mixin:
'use strict';
var _ = lodash;
var DragDropMixin = {
/*
* usage:
*
* mixins: [DragDropMixin],
* dragDrop: function () {
*
* return {
*
* // when dragging an item
* draggable: true,
* dropType: 'myItem',
* dataTransfer: { myItemData: property }
*
* // when dropping an item:
* droppable: true,
* acceptableDrops: ['myItem'],
* drop: function (myItem) {},
* };
* }
*
*/
isAttrEnabled: function (attr) {
return this.dragDropData && this.dragDropData[attr];
},
isDroppable: function () {
return this.isAttrEnabled('droppable');
},
isDraggable: function () {
return this.isAttrEnabled('draggable');
},
componentDidMount: function () {
var node = this.getDOMNode();
this.dragDropData = this.dragDrop();
if (this.isDroppable()) {
node.addEventListener('dragover', this.handleDragOver, this);
node.addEventListener('drop', this.handleDrop, this);
}
if (this.isDraggable()) {
node.draggable = true;
node.addEventListener('dragstart', this.handleDragStart, this);
}
},
componentWillUnmount: function () {
var node = this.getDOMNode();
if (this.isDroppable()) {
node.removeEventListener('dragover', this.handleDragOver);
node.removeEventListener('drop', this.handleDrop);
}
if (this.isDraggable()) {
node.removeEventListener('dragstart', this.handleDragStart);
}
},
handleDragOver: function (e) {
e.preventDefault();
},
handleDrop: function (e) {
var jsonData = e.dataTransfer.getData('objToPass'),
passedObj = JSON.parse(jsonData),
acceptableDrops = this.dragDropData.acceptableDrops;
e.preventDefault();
if (!this.dragDropData.drop) {
throw new Error('Must define drop function when using droppable');
}
if (_.includes(acceptableDrops, passedObj.dropType)) {
this.dragDropData.drop(passedObj.data);
}
},
handleDragStart: function (e) {
var objToPass = {
data: this.dragDropData.dataTransfer,
dropType: this.dragDropData.dropType
};
e.dataTransfer.setData('objToPass', JSON.stringify(objToPass));
}
};
Thanks again.
OK, got it.
I was actually listening to native events and simulating React synthetic events.
Fixed it by changing the mixin:
componentDidMount: function () {
var node = this.getDOMNode();
this.dragDropData = this.dragDrop();
if (this.isDroppable()) {
node.ondragover = this.handleDragOver;
node.ondrop = this.handleDrop;
}
if (this.isDraggable()) {
node.draggable = true;
node.ondragstart = this.handleDragStart;
}
},
And testing by triggering a native event
nodeDrag.ondragstart(mockEvent);
nodeDrop.ondragover(mockEvent);
nodeDrop.ondrop(mockEvent);
expect(DragDropMixin.handleDrop).toHaveBeenCalled();
expect(renderedDrop.state).toBeNull();

File Reading Failing

The script is being ran on the android OS at the moment.
Globals File
///Store Global Variables
var Globals = {
Storage: window.localStorage,
OfflineMode: false,
GetSettingsString : function()
{
return JSON.stringify(Settings);
},
SetSettings : function(str)
{
try
{
Settings = JSON.parse(str);
if(Settings.Id != 0)
VelocityMeetings.app.navigate("scan/", { root: true });
}
catch(e)
{
alert(e);
Globals.SetSettings();
}
},
///Experimentation Function
SetSettings: function () {
//Settings = JSON.parse(str);
Settings.OfflineMode = false,
Settings.Username = "mager1794",
Settings.Password = "mn1apwfm",
Settings.Id = 0;
alert("Values Set Manually");
//VelocityMeetings.app.navigate("scan/", { root: true });
},
Init: function () {
// this.SetSettings(/*FileStream.ReadFile("settings.dat")*/);
alert("test2");
this.SetSettings(FileStream.ReadFile("settings.dat"));
alert("test3");
},
Save: function () {
FileStream.WriteFile("settings.dat", GetSettingsString());
}
};
document.addEventListener("deviceready", ondeviceReady(), false);
// Cordova is ready to be used!
//
function ondeviceReady() {
alert("test");
Globals.Init();
}
FileSystem File
var FileStream = {
WriteFile: function (filename, objtoWrite) {
_filename = filename;
_dataobj = objtoWrite;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, _gotFSWrite, fail);
},
WriteFile: function (filename, objtoWrite, type) {
_filename = filename;
_dataobj = objtoWrite;
_type = type;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, _gotFSWrite, fail);
},
ReadFile: function (filename) {
alert("ReadFile Called");
_filename = filename;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, _gotFSRead, fail);
return _dataread;
},
_dataread: null,
_dataobj: null,
_type : "WRITE",
_filename: "",
_gotFileWriter: function (writer) {
writer.onwrite = function (evt) {
_isBusy = false;
};
if(_type=="WRITE")
writer.write(_dataobj);
if (_type == "APPEND")
{
writer.seek(writer.length);
writer.write(_dataobj);
}
writer.abort();
},
_gotFSWrite: function (fileSystem) {
fileSystem.root.getFile(_filename, { create: true }, _gotFileEntryWrite, fail);
},
_gotFileEntryWrite: function (fileEntry) {
fileEntry.createWriter(_gotFileWriter, fail);
},
_gotFSRead: function (fileSystem) {
alert("gotFSRead Called");
fileSystem.root.getFile(_filename, { create: true }, _gotFileEntryRead, fail);
},
_gotFileEntryRead: function (fileEntry) {
alert("gotFileEntryRead Called");
fileEntry.file(_gotFileRead, fail);
},
_gotFileRead: function (file) {
alert("gotFileRead Called");
var reader = new FileReader();
reader.onloadend = function (evt) {
_dataread = evt.target.result;
};
reader.readAsText(file);
},
_fail: function (error) {
throw "File Failed";
}
};
the GotFSRead function is never being reached and I cannot figure out why, I've placed in the alerts just so I can watch as it progressed through the functions. Additionally, can you store a callback in a variable? because it seems that the read file function is going to need a callback in order to successfully receive the data.
Yes, in Javascript functions are objects, so they can be assigned to variables just like you're doing in your code here.
The function references in your FileStream object are missing this references, such as this._gotFSRead. For example:
ReadFile: function (filename) {
alert("ReadFile Called");
this._filename = filename;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, this._gotFSRead, this._fail);
return this._dataread;
},
There are many places where this is missing, and you need to fix your _fail references too.

Images from Backstretch(backstretch.js) in onepage creeping in to other page's backstretch in Durandal.js

I have used Durandal.js for my SPA. I need to have slideshow of Images as background in certain pages, for which I am using jquery-backstretch. I am fetching images from my web back-end. Everything works fine while navigating between pages in normal speed. But, when I navigate from one of the pages which has backstretch to another one with backstretch very rapidly, Images from backstretch in first page also creeps in second page. When I debugged, only the correct Images were being passed to second page. And also the slideshow is not running in a proper interval. So it must be both the backstretches being invoked.
Please tell me how I can stop the previous backstretch from appearing again. Here are the relevant code snippets.
This is my first page's(with backstretch) viewmodel code.
var id = 0;
var backstetcharray;
function loadbackstretchb() {
backstetcharray = new Array();
$.each(that.products, function (i, item)
{
if(item.ProductBackImage != "")
{
backstetcharray.push("xxxxxxxxxx" + item.ProductBackImage);
}
}
);
$.backstretch(backstetcharray, { duration: 5000, fade: 1500 });
}
var that;
define(['plugins/http', 'durandal/app', 'knockout'], function (http, app, ko) {
var location;
function callback() {
window.location.href = "#individual/"+id;
// this.deactivate();
};
return {
products: ko.observableArray([]),
activate: function () {
currentpage = "products";
that = this;
return http.get('yyyyyyyyyyyyyyy').then(function (response) {
that.products = response;
loadbackstretchb();
});
},
attached: function () {
$(document).ready(function () {
$('.contacticon').on({
'mouseenter': function () {
$(this).animate({ right: 0 }, { queue: false, duration: 400 });
},
'mouseleave': function () {
$(this).animate({ right: -156 }, { queue: false, duration: 400 });
}
});
});
$(document).ready(function () {
$(".mainmenucont").effect("slide", null, 1000);
});
//setTimeout($(".mainmenucont").effect("slide", null, 1000), 1000);
$(document).on("click", ".ind1", function (e) {
// alert("ind1");
id = e.target.id;
// $(".mainmenucont").effect("drop", null, 2000, callback(e.target.id));
$('.mainmenucont').hide('slide', { direction: 'left' }, 1000, callback);
});
}
}
});
This is my second page's(with backstretch) viewmodel code.(To where I am navigating)
var recs;
var open;
var i, count;
var backstetcharray;
function loadbackstretchc() {
backstetcharray = new Array();
$.each(recs, function (i, item) {
if (item.BackgroundImage != "") {
backstetcharray.push("xxxxxxxxxx" + item.BackgroundImage);
}
}
);
$.backstretch(backstetcharray, { duration: 5000, fade: 1500 });
}
var that;
define(['plugins/http', 'durandal/app', 'knockout'], function (http, app, ko) {
var system = require('durandal/system');
var location;
function menucallback() {
window.location.href = location;
// this.deactivate();
};
return {
activate: function (val) {
currentpage = "recipes";
open = val;
that = this;
var pdts;
recs;
var recipeJson = [];
http.get('yyyyyyyyyyyyyy').then(function (response) {
pdts = response;
http.get('yyyyyyyyyyyy').then(function (response1) {
recs = response1;
loadbackstretchc();
$.each(pdts, function (i, item) {
var json = [];
$.each(recs, function (j, jtem) {
if (item.DocumentTypeId == jtem.BelongstoProduct) {
json.push(jtem);
}
});
jsonitem = {}
jsonitem["product"] = item.ProductName;
jsonitem["link"] = "#" + item.UmbracoUrl;
jsonitem["target"] = item.UmbracoUrl;
jsonitem["recipes"] = json;
recipeJson.push(jsonitem);
});
// that.products = recipeJson;
count = recipeJson.length;
i = 0;
return that.products(recipeJson);
});
});
},
attached: function(view) {
$(document).ready(function () {
$('.contacticon').on({
'mouseenter': function () {
$(this).animate({ right: 0 }, { queue: false, duration: 400 });
},
'mouseleave': function () {
$(this).animate({ right: -156 }, { queue: false, duration: 400 });
}
});
});
$(document).ready(function () {
$(".mainmenucont").effect("slide", null, 1000);
});
$(document).on("click", ".recipeclick", function (e) {
console.log(e);
location = "#recipe/" + e.target.id;
$('.mainmenucont').hide('slide', { direction: 'left' }, 1000, menucallback);
});
$(document).on("click", ".locclick", function (e) {
if (e.handled != true) {
if (false == $(this).next().is(':visible')) {
$('#accordion ul').slideUp(300);
}
$(this).next().slideToggle(300);
e.handled = true;
}
});
},
products: ko.observableArray([]),
expand: function() {
++i;
if (i == count) {
$("#" + open).addClass("in");
}
}
};
});

What is the difference between plug-in-type methods and methods in a global variable

In terms of efficiency,
what's the fastest and most standard way to tweak a function in javascript?
Plugin-style coding would be like this.
; (function ($, window, document, undefined) {
var pluginName = "SoketManager",
dataPlugin = "plugin_" + pluginName,
settings = {
target: this,
width: 350,
height: 150,
theme: 'default'
}
var Plugin = {
// instance...
}
Plugin.prototype = {
connect: function() {
//something.
},
disconnect: function() {
//something.
},
sendmessage: function() {
//something...
},
etc: function() {
}
//etc2: function() .......
}
$.fn[pluginName] = function (arg, contents) {
var args, instance;
if (typeof arg === 'string' && typeof instance[arg] === 'function') {
args = Array.prototype.slice.call(arguments, 1);
return instance[arg].apply(instance, args);
}
And using global variable would be like this..
var SocketManager = {
sock: '',
connect: function () {
var stdInfo = new JSONClientParameters();
var socket = io.connect('http://192.168.1.39:3000', {
query: stdInfo.toGetString()
//'reconnect': true,
// 'reconnection delay': 500,//default 500
//'max reconnection attempts': 10
});
kdbSocketManager.ksock = socket;
socket.on('connect', function () {
alert('successfully connected to the database!!');
});
},
disconnect: function () {
this.ksock.disconnect();
},
sendMessage: function (pMsg, pTargetId) {
this.ksock.emit('sendMessage', { msg: pMsg, targetId: pTargetId });
},
I see no point in coding like the plugin-way. Is it much more simple and easy to read to code like the latter one? could somebody explain this in detail?

fine-uploader trouble with formatting the code, events

I need to have multiple events associated with the fineuploader instantiation, but I'm not sure how to go about it. Can't they be added within the fineuploader properties, etc.? Isn't the complete event then called onComplete? Is there an example that exists? Also, I'm confused about the number of closing brackets, etc. When I originally cut and pasted this code in, there was an extra )}; that sat outside. I removed that, but I'm not sure if that's cool or not for the actual code. Any help is appreciated, as I've been toying with this for hours. Some variables have been set outside this code.
$(document).ready(function () {
var controlType = '#Model.ControlType';
var surveyItemResultId = #Model.Results[0].SurveyItemResultId;
var itemId = #Model.SurveyItemId;
var instance = #Model.Results[0].SurveyInstanceID;
var loopingCounter = 0;
var fineuploader = $('#files-upload').fineUploader({
request:
{
endpoint: '#Url.Action("UploadFile", "Survey")',
customHeaders: { Accept: 'application/json' },
params: {
surveyInstanceId: (function () { return instance; }),
surveyItemResultId: (function () { return surveyItemResultId; }),
itemId: (function () { return itemId; }),
loopingIndex: (function () { return loopingCounter++; })
}
},
validation: {
acceptFiles: ['image/*','application/pdf','text/csv'] ,
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png', 'csv', 'pdf'],
sizeLimit: 1024*1024*1 // 1MB
},
multiple: true,
text: {
uploadButton: '<i class="icon-plus icon-white"></i>Select your upload file(s)'
}
})
.on('complete', function(event, id, fileName, responseJSON) {
alert("Success: " + responseJSON.success);
uploadedFileCounter++;
if (filesToUpload == uploadedFileCounter)
{
alert("DONE UPLOADING!");
}
}).on('submitted', function(event, id, filename) {
filesToUpload++;
alert("submitted: " + filesToUpload);
}
});
});
Your code is littered with syntax and other errors. First off, you are referencing filesToUpload and uploadedFileCounter variables that are not defined anywhere in your code. Second, you have an extra closing bracket in your code.
There are also some formating issues with your code. First, Your code is inconsistently indented. Second, you are mixing placement of curly brackets.
Here is your original code with my adjustments:
$(document).ready(function () {
var controlType = '#Model.ControlType',
surveyItemResultId = #Model.Results[0].SurveyItemResultId,
itemId = #Model.SurveyItemId,
instance = #Model.Results[0].SurveyInstanceID,
loopingCounter = 0,
filesToUpload = 0,
uploadedFileCounter = 0;
var fineuploader = $('#files-upload').fineUploader({
request: {
endpoint: '#Url.Action("UploadFile", "Survey")',
customHeaders: { Accept: 'application/json' },
params: {
surveyInstanceId: (function () { return instance; }),
surveyItemResultId: (function () { return surveyItemResultId; }),
itemId: (function () { return itemId; }),
loopingIndex: (function () { return loopingCounter++; })
}
},
validation: {
acceptFiles: ['image/*','application/pdf','text/csv'] ,
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png', 'csv', 'pdf'],
sizeLimit: 1024*1024*1 // 1MB
},
multiple: true,
text: {
uploadButton: '<i class="icon-plus icon-white"></i>Select your upload file(s)'
}
})
.on('complete', function(event, id, fileName, responseJSON) {
alert("Success: " + responseJSON.success);
uploadedFileCounter++;
if (filesToUpload == uploadedFileCounter) {
alert("DONE UPLOADING!");
}
}).on('submitted', function(event, id, filename) {
filesToUpload++;
alert("submitted: " + filesToUpload);
});
});

Categories