CKEditor uploadimage change name=upload - javascript

I use plugin uploadimage CKEditor.
How to properly configure the plugin to transfer its name to the field, rather than the standard application.
Upload URL:
config.filebrowserUploadUrl = '/uploadfiles.nsf/uploadfiles?CreateDocument';
plugin use:
<input type="file" name="upload">
It should be like this:
<input type="file" name="%%File.4325814d00377965.3570884048d1a3c44325812a003cb5ad.$Body.0.96">
Tell me which parameter is responsible for this

You can modify the default file upload behavior before sending the request as follows -
// Get CKEditor instance
var editor = CKEDITOR.instances.editor1;
// Modify CKEditor's default request data object on 'fileUploadRequest' event
editor1.on('fileUploadRequest', function(evt) {
// Copy contents of 'upload' image field to a new field with 'new_name'
var requestDataObject = evt.data.requestData;
requestDataObject['new_name']=requestDataObject['upload'];
// Delete old 'upload' image field from the request data object
delete requestDataObject['upload'];
} );
Here's the official documentation where they talk about editing the default request object with new headers and data items - https://ckeditor.com/docs/ckeditor4/latest/guide/dev_file_upload.html#editor-side-configuration.
Unfortunately, they leave it to you to figure out a way to modify the existing 'upload' field by simply saying -
Note that the default file to be uploaded is also a property of
evt.requestData named upload and it can be overwritten when
neccessary.

You can get your file's name in the response of your server.
see a example in php :
if (file_exists("img/" . $_FILES["upload"]["name"]))
{
echo $_FILES["upload"]["name"] ;
}
you can also see the documentation of CKEditor on upload file : http://docs.ckeditor.com/#!/guide/dev_file_upload

Related

Not getting file data in Extjs Ajax request

I have a form on form-window, and inside form window I have a form with many fields and one upload button. When try to submit form using Ajax.request I have got textfield value but can not get file data. Except filename.
var fd = Ext.getCmp('users-form').form;
var fileInput = document.getElementById('company_logo');
console.log(fd.getEl().dom.files);
params = {
name : fd.findField('name').getValue(),
login : fd.findField('login').getValue(),
email : fd.findField('email').getValue(),
password : fd.findField('password').getValue(),
password_repeat : fd.findField('password_repeat').getValue(),
id : fd.findField('id').getValue()
company_logo : fd.findField('logo').getValue()
}
console.log(params);
Ext.Ajax.request({
url: Scada.reqUrl('users', 'save'),
method: 'post',
params: {
data: Ext.encode(params)
},
success: function() {
console.log('in success');
},
failure: function() {
console.log('in failure');
}
});
Here logo is input type file. I want to send logo data with ajax request. Please help me to figure out the problem. Thanks
Not sure why you started a new question instead of editing Encode form data while fileupload true in Extjs Form Submit as this seems to be the same problem.
Assuming logo is your file upload field you are trying to get the file data using getValue does not actually return the file content (if you use modern there is a getFiles method which returns the selected file objects).
General problems with your approach:
As I stated in my original answer it is not a good idea to send files in a standard ajax request. In your case those problems are:
If you expect getValue to return file contents, you are potentially encoding binary data into a JSON string. This will maybe work but create a large overhead and as the only available JSON datatype that could handle this content is string your parser would have to guess that property company_logo contains binary data and needs to be somehow converted into some sort of file reference.
You are sending files without metadata, so when just adding the raw content into your JSON string you would not be able to detect the expected file type without testing the file in multiple ways
As far as I know you would not be able to access the file content in classic toolkit at all
Submitting the data as a form: In your original question you explained that you submit the form instead of doing Ajax requests which is generally the preferred way.
When you submit a form that contains a file upload field the form will automatically be submitted as multipart/form-data the raw files are added to the request body with it's original content while preserving metadata collected by the browser.
If you look at https://docs.sencha.com/extjs/7.0.0/modern/Ext.Ajax.html#method-request you would have to set isUpload to true and use the form proeprty instead of params, passing a reference to the parent form.

Saving Javascript FormData() Object on client side

I have a html page which contains a form element with some text and file input elements.
This from is submitted with an ajax call to the server using a method suggested here: How can I upload files asynchronously?
As you may see in the referenced page from the above link, the FormData() object is used as a container for inputed data and I have done the job successfully.
But now we want to create a new page that have these html elements, save the text and file inputs on client side (Cookie or Local Strorage or . . .) and do the ajax submit later on another page.
I wasn`t able to save new FormData() in either cookie or local storage; what got saved is a small string:"[object FormData]" instead of entered file and strings.
I also tried using JSON.stringify() with no success; it just returned an empty JSON("{}").
(the code is using jQuery selector)
var postData = new FormData($(form)[0]);
// var sPostedData = JSON.stringify(postData); // returns: "{}"
var myStorage = window.localStorage; // returns: "[object FormData]"
myStorage.setItem("contentOrder", postData);
Please help, how should I save this object on my client-side?
To get the file from form data use formData.get('file') where file is the name of an input. The returned object will be of type Blob (see how to get its content).
The complete example can be found in this fiddle: https://jsfiddle.net/skm5m467/1/

Additional parameters when using intel.xdk.file.uploadToServer?

I'm using Intel XDK to create a smartphone application. Currently I'm uploading a captured photograph by using intel.xdk.file.uploadToServer as shown in their documentation. This is working fully, however I would like to send additional parameters to the back-end (PHP) other than just those required by the 'uploadToServer' function.
What should I do / use?
The uploadToServer file API does not allow you to specify additional parameters than what is documented.
I would use Parse JavaScript APIs that allow you to easily save an object and link to an uploaded file, here is an example:
Parse.initialize("YOUR KEY GOES HERE"); //API key
//whatever you want to call your storage object
var PhotoDetails = Parse.Object.extend("PhotoDetails");
//create new instance of your Parse Object
var photoDetails = new PhotoDetails();
//you can add each param separately and save
photoDetails.set("paramname", "value");
photoDetails.save();
//or use object literal notation
photoDetails.save({category: "landscape",
description: "a very cool photo",
location: "33.38453, -28.234234"
}).then(function(object) {
alert("Photo Recorded!);
});
You can also store the actual photo or filetype in the cloud up to 10MB per file. Parse determines the file type by the file extension or you can specify the type in the optional third param below:
//see https://parse.com/docs/js_guide#files
//for base 64 or HTML file input examples
var parseFile = new Parse.File("myphoto.jpg", fileData, "image/jpg");
parseFile.save().then(function() {
alert("The file has been saved to Parse.");
}, function(error) {
console.log("The file either could not be read, or could not be saved to Parse.");
});
You can associate a Parse File with a Parse Object by using:
photoDetails.set("photoFile", file);
photoDetails.save();
Then in the cloud you can login to Parse and you will see your object type in the Data Browser view with your photo image and all the other params you specified.
For more info see: https://parse.com/docs/js_guide#javascript_guide

Convert a Json Object to a file Object

I have some java-script functions. I am using input type file for selecting multiple files. In the on-change event I am getting a list files objects which were uploaded and then I am storing those objects in a hidden field. I want to retrieve those objects as file objects only. How can i accomplish that?
The code I am using is as follows:-
<input type="file" multiple onchange="ehDisplayFileNames(event);" />
function ehDisplayFileNames(event) {
myFilesList = $('#' + event.target.id)[0]; // $('#chooseFiles')[0] gives the DOM element of the HTML Element as opposed to $('#store-input') which gives the jQuery object
$("#FilesToUpload").val(JSON.stringify(filesToUpload));
}
function getAllFiles(){
var filesToUpload = [];
filesToUpload = $.parseJSON($("#FilesToUpload").val()); // returns json objects instead i need file objects
}
Thank you for the help.
I was looking for a similar thing.. I ended up using the solution provided here as there is no way to serialize API object... https://stackoverflow.com/a/20535454/606810
Here is another source i found useful for image/file storage: https://hacks.mozilla.org/2012/02/saving-images-and-files-in-localstorage/
Hope it helps!
whats a file Object? You mean JSON string to JS Object?
If yes just use:
var myObject = jQuery.parseJSON( jsonString ) ;
and it will be a object
REWRITE::
<input type="file" multiple onchange="ehDisplayFileNames(event);" />
add ID to it
<input type="file" id="myFile" multiple onchange="ehDisplayFileNames(event);" />
then you have your object:
$("#myFile")
Here is the solution you are looking for. :-)
I assume what you are ultimately trying to do is to store the values (of which there may be multiples). In addition, you may be trying to display them to the user instead of showing the default text that says "4 files selected" for example. And also, as you had indicated, you want to be able to programmatically manipulate the list of selected files.
The problem is that can't be done in the way you are approaching it. That's because the <input type="file" /> element is protected, and the full file path will never be accessible. Therefore, when you attempt to grab the values, they would only be the filenames themselves but not the full file path. For example, if you selected a file called dog.jpg from your desktop, the browser knows the path is "file:\c:\windows\users\someuser\desktop\dog.jpg" but when you programmatically try to retrieve it - you will only get the value "dog.jpg". With just the filename, you can not reconstruct the full file paths and so you can't do anything meaningful with them in regards to eventually sending them to be processed by the server.
Therefore, I have crafted a solution for you which uses a single file upload button. When a user selects a file, it will add another as needed. In addition, when there are more than one files selected, the user can choose to remove any of them as needed.
You would process the selected files on your server in the following way... When the form data is sent to the form action (in this case "/sendfiles"), your server side code would process the incoming data for each form element. In the example below, the input elements of type files (having the name attribute "myFiles") would be sent as an array, where each array element would contain the file data of each one that was specified by the user.
jQuery code:
var getUploadFragment = function(){return $('<div class="files-cont"><input type="file" name="myfiles" class="files" /></div>')};
$(document).ready(function(){
$("#my_form")
.append(getUploadFragment())
.on("change", "input[name=myfiles]:last", function(){
var lastFileContainer = $(".files-cont:last");
lastFileContainer.after(getUploadFragment());
if($(".files-cont").length > 1){
lastFileContainer.append('[Remove]');
}
})
.on("click", ".remove", function(){
if($(".files-cont").length > 1){
$(this).parent().remove();
}else{
$(this).remove();
}
});
});
with the following form defined in the body:
<form id="my_form" action="/sendfiles" method="post"></form>

plupload - send another request parameter with uploaded file

plupload creates nice ids in file object. How this id can be sent to the upload script?
The upload script has 3 variables in $_POST - file name, chunk number and total number of chunks.
How to add another parameter to plupload's POST request (in my case, the file.id)?
The first step would be to add a handler to the BeforeUpload event.
Then, if you are using multipart, you can change the uploader settings to dynamically set different multipart params:
plupload_instance.bind('BeforeUpload', function (up, file) {
up.settings.multipart_params = {fileid: file.id}
});
(warning: this example overrides any and all multipart_params, you can play it smarter than that by just setting fileid)
if you are not using multipart, your only options would be to pass the argument as a header, or to manually add the param to the URL for each file (these 2 options should also be done within BeforeUpload).
Note that when not using multipart, plupload will add the name and chunk params to the URL after any URL you already set for the uploader, for each file, so this is where extra params go.

Categories