I would like to set the request endpoint of fine-uploader dynamically.
For example:
$('#jquery-wrapped-fine-uploader').fineUploader({
request: {
endpoint: submitUrl
},
multiple: false,
button: $("#uploader-button"),
// etc...
});
submitUrl must be already set in the page and can't be changed.
I would like to do something more dynamic, something like:
request: {
endpoint: function() { ($('#submitUrlField').val() }
}
But the above sends the request to
function%20()%20%7B%20$(%27#submitUrlField%27).val()%20}
Grateful for anyone who knows how to do this!
You can use multi enpoints.
For example use several endpoint for odd/even uploads:
callbacks: {
onUpload: function(id, name) {
var endpoint = endpoints[id % endpoints.length];
this.setEndpoint(endpoint.url, id);
this.setParams({
signature: endpoint.signature,
params: endpoint.params,
ajax: true
}, id);
}
}
If the file is big and you have enabled the chunking, you can't change the endpoint url dinamically.
My solution is use the event
callbacks:{
onComplete:function(id,name,responseJSON,xhr) {
console.log('> onComplete. id=' + id);
console.log('> onComplete. name=' + name);
console.log('> onComplete. responseJSON=' + JSON.stringify(responseJSON));
console.log('> onComplete. uuid=' + responseJSON.uuid);
if (responseJSON.success)
{
// call a httpRequest with the url you want.
}
}
}
One useful example for the setEndpoint method. This code will set endpoint based on uploading file type:
callbacks: {
onUpload: function(id, name) {
var file = this.getFile(id);
var fileType = file.type;
this.setEndpoint(endpointList[fileType], id);
}
}
Your endpointList:
var endpointList = {
'image/png': 'url/uploadimage',
'video/mp4': 'url/uploadvideo',
'text/plain': 'url/uploadtext'
}
your old code:
request: {
endpoint: function() { ($('#submitUrlField').val() }
}
|_ why need ( becasue it has not close ) match
try one of these
request: {
endpoint: function() { return $('#submitUrlField').val() } // here you had `(`
}
or
request: {
endpoint: $('#submitUrlField').val()
}
Related
I currently have a database with 2 objects:
Role
Permission
ONE Role can have MANY permissions. I currently have my Role adapter setup as:
export default DS.RESTAdapter.extend(DataAdapterMixin, {
namespace: 'v1',
host: ENV.APP.API_HOST,
authorizer: 'authorizer:application',
pathForType: function(type) {
return 'staff/roles';
}
});
By default, when a Permission is added to a Role, it generates this request:
Request:
PUT /v1/staff/roles/1
Body:
{
"name": "name_of_role"
"permissions": [
{
"id": "3",
"name": "name_of_permission"
},
...
]
}
I'd like to customize my adapter to produce a request that looks like this instead:
Request:
PUT /v1/staff/roles/1/permissions/3
Body:
<None>
Can someone please tell me how I can go about doing this? Updating the server api to accommodate Ember JS is unfortunately not an option.
UPDATE:
Based on Ryan's response, here's a (I'll call it messy) workaround that did the trick for me.
Open to suggestions for making this more elegant:
export default DS.RESTAdapter.extend(DataAdapterMixin, {
namespace: 'v1',
host: ENV.APP.API_HOST,
authorizer: 'authorizer:application',
pathForType: function(type) {
return 'staff/roles';
},
updateRecord: function(embestore, type, snapshot) {
var roleID = snapshot.id;
var permissionID = snapshot.adapterOptions.permissionID;
var url = ENV.APP.API_HOST + "/v1/staff/roles/" + roleID + "/permissions/" + permissionID;
return new Ember.RSVP.Promise(function(resolve, reject){
Ember.$.ajax({
type: 'PUT',
url: url,
headers: {'Authorization': 'OAUTH_TOKEN'},
dataType: 'json',
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
},
});
I can't find it in the Ember documentation but there is a universal ajax method attached to adapter that you can override.
So in my adapter to fit our auth scheme I've done this:
export default DS.RESTAdapter.extend({
host: ENV.host,
ajax: function(url, method, hash){
if(hash){
if(hash.data !== undefined && hash.data !== null){
hash.data.sessionId = this.getSessionId();
}
}else {
hash = {
data: {}
};
hash.data.sessionId = this.getSessionId();
}
return this._super(url, method, hash);
},
getSessionId: function(){
return window.sessionStorage.getItem('sessionId') || {};
}
}
This attaches the sessionId to every ajax call to the server made though out the entire application.
Changing it to modify your url based on the hash arguments passed in shouldn't be an issue.
My version of ember is 2.3.2 but I'm on the latest stable(2.5.2) version of ember-data and this is still working great in case you are worried about the age of that blog post I found.
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);
}
}
From client-side javascript I want to call a share-webscript which returns JSON data.
The response from getTicket.json.ftl looks like:
{
"ticket" : "TICKET_faf851d4a993b62c98908268af07876f09fa86c9"
}
So how can I call this share-webscript from my client-side javascript and extract the value of "ticket" ?
see answer below
Answer:
Alfresco.util.Ajax.jsonGet(
{
url: Alfresco.constants.PROXY_URI + "/auth/getTicket.json",
successCallback:
{
fn: function(response)
{
try {
var json = JSON.parse(response.serverResponse.responseText);
var ticket = json["ticket"];
if (ticket.substring(0, 6) == "TICKET") {
clipboardData.setData("Text", ticket + "&" + file.nodeRef);
location.href = Alfresco.constants.URL_RESCONTEXT + "components/javawebstart/AEF_JNLP.jnlp";
} else {
// handle unknown format
}
} catch (e) {
// handle error
}
},
scope: this
},
failureCallback:
{
fn: function(response)
{
// handle failure case
},
scope: this
}
});
This calles the share tier webscript. So you also need a share tier webscript which calls a repository web script which returns the actual ticket ...
In my app, every KiiUser has one hash table of data. But I have some problems using KiiObject to save data and get it next time.
I want to create an KiiObject with a specific URI when user registers so every time he logins I can import it with
KiiObject.objectWithURI(<URI>)
Alternatively, how to use objectWithJSON().
I don't want to use kiiQuery if I can avoid, as there is only one object for each user.
Can anyone give me an example of code how to create this Kiiobject when user registers and how to edit it every time he logins ; or every time he edits it and saves.
that's some of my current code but i don't get always the saved data back (the saved hash table "data" undefined on the object)
function performRegistration() {
try {
var user = KiiUser.userWithUsername(<username>, <password>);
user.register({
success: function(Auser) {
var bucket = Auser.bucketWithName("data");
data = bucket.createObject();
data.set("data", {});
data.saveAllFields({
success: function(theObject) {
console.log("Object saved!");
theObject.refresh({success:function(obj){
data=obj;
[....
...Some Code here to edit the...
...data object and save it....
...]
Kii.logger("User registered: " + Auser);
}});
},
failure: function(theObject, errorString) {
console.log("Error saving object: " + errorString);
}
});
},
failure: function(theUser, anErrorString) {
alert("Unable to register: " + anErrorString);
Kii.logger("Unable to register user: " + anErrorString);
}
});
} catch (e) {
alert("Unable to register: " + e.message);
Kii.logger("Unable to register user: " + e.message);
}
}
// the user clicked the 'sign in' button
function performLogin() {
KiiUser.authenticate(<username>, <password>, {
success: function(Auser) {
user = Auser;
var bucket = user.bucketWithName("data"); // a KiiBucket
var query = KiiQuery.queryWithClause();
var queryCallbacks = {
success: function(queryPerformed, r, nextQuery) {
console.log(r.constructor.name,r);
r[0].refresh({success:function(obj){
data=obj;
if(data.get("data")==undefined){
data.set("data",{});
}
data.save({success:function(Sobj){
data=Sobj;
[...
...some data object manipilation then save it
...]
}});
}});
},
failure: function(queryPerformed, anErrorString) {
}
};
bucket.executeQuery(query, queryCallbacks);
},
// callback for failed registration
failure: function(theUser, anErrorString) {
alert("Unable to register: " + anErrorString);
Kii.logger("Unable to register user: " + anErrorString);
}
});
};
Kii.initializeWithSite(<...>, <...>, KiiSite.US);
[...
other code
...]
How about using KiiUser's custom fields?
It is described as "Manipulating the custom fields" in this page.
http://documentation.kii.com/en/guides/javascript/managing-users/user-attributes/
Check these links for detail of API:
http://documentation.kii.com/references/js/storage/latest/symbols/KiiUser.html#set
http://documentation.kii.com/references/js/storage/latest/symbols/KiiUser.html#get
I have tried this, but it didn't satisfy my request at all. I write a new one:
var file_system;
var fs_root;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 1024*1024, onInitFs, request_FS_fail);
function onInitFs(fs) {
file_system= fs;
fs_root= file_system.root;
alert("ini fs");
create_Directory();
alert("ini fs done.");
}
var string_array;
var main_dir= "story_repository/"+ User_Editime;
string_array= new Array("story_repository/",main_dir, main_dir+"/rec", main_dir+"/img","story_repository/"+ User_Name );
function create_Directory(){
var start= 0;
var path="";
while(start < string_array.length) {
path = string_array[start];
alert(start+" th created directory " +" is "+ path);
fs_root.getDirectory(
path,
{create: true, exclusive: false},
function(entry) {
alert(path +"is created.");
},
create_dir_err()
);
start++;
}//while loop
}//create_Directory
function create_dir_err() {
alert("Recursively create directories error.");
}
function request_FS_fail() {
alert("Failed to request File System ");
}
Although the directories are created, the it sends me
ErrorCallback:"alert("Recursively create directories error.");"
First, I don't think this code will work since I have tried this, which failed:
window.requestFileSystem(
LocalFileSystem.PERSISTENT,
0,
//request file system success callback.
function(fileSys) {
fileSys.root.getDirectory(
"story_repository/"+ dir_name,
{create: true, exclusive: false},
//Create directory story_repository/Stallman_time.
function(directory) {
alert("Create directory: "+ "story_repository/"+ dir_name);
//create dir_name/img/
fileSys.root.getDirectory {
"story_repository/"+ dir_name + "/img/",
{create: true, exclusive: false},
function(directory) {
alert("Create a directory: "+ "story_repository/"+ dir_name + "/img/");
//check.
//create dir_name/rec/
fileSys.root.getDirectory {
"story_repository/"+ dir_name + "/rec/",
{create: true, exclusive: false},
function(directory) {
alert("Create a directory: "+ "story_repository/"+ dir_name + "/rec/");
//check.
//Go ahead.
},
createError
}
//create dir_name/rec/
},
createError
}
//create dir_name/img
},
createError
);
},
//Create directory story_repository/Stallman_time.
createError());
}
I just repeatedly call fs.root.getDirectory only but it failed. But the first one is almost the same...
What is the problem at all? Why does the first one always gives me the ErrorCallback?
Why can't the second one work?
Does anyone has a better solution? (no ErrorcallBack msg)
ps: I work on Android and PhoneGap 1.7.0.
I am not able to figure out mistake in your code. I have a library written to do localIO via PhoneGap 2.0. I have abstracted code for your requirements from there. See if it works for 1.7. I have not tested the code after abstraction. You may need to fix error, if any.
var fsroot = fs.root; // initialize this
function fileGetDir(path, cb) {
var fnGetOrCreateDir = function(p, de) {
var entry = p.shift();
if (entry) {
de.getDirectory(entry, {
create : true
}, function(dirEntry) {
fnGetOrCreateDir(p, dirEntry);
}, fileFSError);
}
else
if (cb) cb(de);
};
if (path) {
var arPath = path.split("/");
fnGetOrCreateDir(arPath, fsroot);
}
else {
if (cb) cb(fsroot);
}
}
function fileFSError(e) {
console.log(e.code);
try {
console.log("fileFSError: " + JSON.stringify(e));
} catch (err) {}
}
function printSuccess(dirEntry) {
console.log(dirEntry.fullPath);
}
// Now create your directories like:
var main_dir= "story_repository/"+ User_Editime;
fileGetDir(mainDir + "/rec", printSuccess);
fileGetDir(mainDir + "/img", printSuccess);
fileGetDir("story_repository/"+ User_Name, printSuccess);
There is a simple file manager for cordova-phoengap:
https://github.com/torrmal/cordova-simplefilemanagement
You can recursively create directories:
//CREATE A DIRECTORY RECURSIVELY
var a = new DirManager(); // Initialize a Folder manager
a.create_r('folder_a/folder_b',Log('created successfully'));
If the first directory off the root "story_repository" does not exist your first call to getDirectory will call the error callback because the call to create dir_name in a non-existent directory will error out on the native side.
Does "story_repository" exist?