file upload using EXT JS - extjs

Steps to create File Upload field using Ext Js

As far as specific steps are concerned, using functionality supported in ExtJS 3x, your best best is to use this module/plugin:
http://dev.sencha.com/deploy/dev/examples/form/file-upload.html
The core script comes with the Ext JS package, in your main HTML file (where you have linked to the core Ext scripts), in the head section after your other scripts put:
<script type="text/javascript" src="nameofyourextfolder/examples/ux/fileuploadfield/FileUploadField.js"></script>
Sadly, there isnt a huge amount of documentation on this element of Ext JS- however for basic functionality, you can create a form with an async upload field using the below:
myuploadform= new Ext.FormPanel({
fileUpload: true,
width: 500,
autoHeight: true,
bodyStyle: 'padding: 10px 10px 10px 10px;',
labelWidth: 50,
defaults: {
anchor: '95%',
allowBlank: false,
msgTarget: 'side'
},
items:[
{
xtype: 'fileuploadfield',
id: 'filedata',
emptyText: 'Select a document to upload...',
fieldLabel: 'File',
buttonText: 'Browse'
}],
buttons: [{
text: 'Upload',
handler: function(){
if(myuploadform.getForm().isValid()){
form_action=1;
myuploadform.getForm().submit({
url: 'handleupload.php',
waitMsg: 'Uploading file...',
success: function(form,action){
msg('Success', 'Processed file on the server');
}
});
}
}
}]
})
What this code will do is create a new formpanel with an upload field and an upload button. When you click the upload button- the selected file will be sent to the serverside script handleupload.php (or whatever you call it). It is then this script that handles what you want to do with the file. An example of this could potentially be:
$fileName = $_FILES['filedata']['name'];
$tmpName = $_FILES['filedata']['tmp_name'];
$fileSize = $_FILES['filedata']['size'];
$fileType = $_FILES['filedata']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc()){
$fileName = addslashes($fileName);
}
$query = "INSERT INTO yourdatabasetable (`name`, `size`, `type`, `file`) VALUES ('".$fileName."','".$fileSize."', '".$fileType."', '".$content."')";
mysql_query($query);
Which would inject the file into a SQL DB. The thing to remember is the server side file handles an upload just as a normal HTML form would...
Hope this helps!

If you look at the examples available at www.ExtJS.com, you'll find this one.
Although it is based on the standard HTML file upload - just like this answer suggests.

setting the id only will result in the $_FILES array name to be the same as the id. If you need to use something else then set the name config option and it will use that instead.

items: {
xtype: 'form',
border: false,
bodyStyle: {
padding: '10px'
},
items: {
xtype: 'multifilefield',
labelWidth: 80,
fieldLabel: 'Choose file(s)',
anchor: '100%',
allowBlank: false,
margin: 0
}
},
Live demo for ExtJS 4.2.2 is here

Related

ExtJS 6 - How to upload a file without using form?

Ext JS provides fileuploadfield which is bundled with a button to browse local files. I just need to upload a file using as soon as it is selected from local instead of using a submit button in order to trigger the post process. Could not find an event which is fired after the file is selected.
p.s. Actually, the version I use is Ext JS 6 but I think the solutions based on previous versions do the work as well.
Form is not required. You can use AJAX and FormData.
var file = s.fileInputEl.dom.files[0],
data = new FormData();
data.append('file', file);
Ext.Ajax.request({
url: '/upload/files',
rawData: data,
headers: {'Content-Type':null}, //to use content type of FormData
success: function(response){ }
});
Online demo here
You will need to use a form if you want to submit the file. Even if you want the button to be in a toolbar, you can enclose it in a form and it will still look like a normal toolbar button (you will need to specify the proper ui config for this).
Example:
dockedItems: [{
dock: 'top',
xtype: 'toolbar',
items: [{
xtype: 'form',
padding: '10 0 0',
url: 'submit/image',
items: {
xtype: 'filefield',
buttonOnly: true,
width: 100,
buttonConfig: {
text: 'Add logo',
width: '100%',
ui: 'default-toolbar-small'
},
listeners: {
change: function (filefield) {
filefield.up('form').submit();
}
}
}
}, {
text: 'Remove logo'
}, '-', {
text: 'Discard changes'
}]
}]
Working fiddle example: https://fiddle.sencha.com/#view/editor&fiddle/1pdk
While I agree with scebotari's answer that in your case embedding a form in the toolbar is probably the easiest solution, for the sake of answering the original question:
If you really cannot or do not want to use a form and you're not limited regarding browser support, have a look at the FileReader.
The idea is to read the file contents on the client side (JavaScript) and then send the data using a regular AJAX request.
Your code could look like that:
function (fileField) {
var file = fileField.fileInputEl.dom.files[0],
reader;
if (file === undefined || !(file instanceof File)) {
return;
}
reader = new FileReader();
reader.onloadend = function (event) {
var binaryString = '',
bytes = new Uint8Array(event.target.result),
length = bytes.byteLength,
i,
base64String;
// convert to binary string
for (i = 0; i < length; i++) {
binaryString += String.fromCharCode(bytes[i]);
}
// convert to base64
base64String = btoa(binaryString);
Ext.Ajax.request({
url: 'save-file.php',
method: 'POST',
params: {
data: base64String
}
});
};
reader.readAsArrayBuffer(file);
}
You are looking for the event change on the fileuploadfield.
The code could look like this:
Ext.create('Ext.form.Panel', {
renderTo: Ext.getBody(),
title: 'Upload Panel',
items: [{
xtype: 'filefield',
name: 'photo',
fieldLabel: 'Photo',
labelWidth: 50,
msgTarget: 'side',
allowBlank: false,
anchor: '100%',
buttonText: 'Select Photo...',
listeners: {
change: function (me, value, eOpts) {
console.log('trigger upload of file:', value);
}
}
}],
});
Fiddle https://fiddle.sencha.com/#view/editor&fiddle/1pd2

Remove fake path in extjs

I am new to the extjs.Please help me to remove fakepath issue in filefield.I do not want to get the exact path .Removing "fakepath" string is ok for me. Code runs perfectly but path displays as C:\fakepath....
I created a seperate window inorder to upload a file. In my case Application should have a seperate window as a result of selecting a option from the menu.
Here is crateWindow function of my code :
createWindow: function() {
var desktop = teamApp.getDesktop();
var win = desktop.getWindow(this.windowId + '_win');
if(!win) {
win = desktop.createWindow({
id: this.windowId + '_win',
title: 'Upload a Audio',
iconCls: 'icon-upload-picture',
height:150,
width: 500,
layout: 'fit',
renderTo: Ext.getBody(),
items:
{
xtype: 'panel',
frame:true,
bodyPadding: '10',
items: [{
xtype: 'filefield',
id: 'form-file',
labelWidth: 100,
//emptyText: 'Select an audio file',
fieldLabel: 'Audio File',
name: 'file-path',
fieldWidth: 250,
allowBlank: false,
anchor: '100%',
buttonText: 'Browse'
}],
buttons: [{
text: 'Save',
handler: function(){
var form = this.up('form').getForm();
if(form.isValid()){
form.submit({
//url: 'file-upload.php',
waitMsg: 'Uploading your Audio file...',
success: function(fp, o) {
msg('Success', 'Processed file "' + o.result.file + '" on the server');
}
});
}
}
}]
}
})
}
win.show();
return win;
}
As far as I understand you cannot, as per documentation at http://docs.sencha.com/extjs/4.1.3/#!/api/Ext.form.field.File
Because there is no secure cross-browser way to programmatically set the value of a file input, the standard Field setValue method is not implemented. The getValue method will return a value that is browser-dependent; some have just the file name, some have a full path, some use a fake path.
Update
What you can do is set fieldWidth to zero and add another textfield before the filefield. You can set the value of this textfield as the name of file selected by user by listening to change of file field and parsing the value from last index of \ till last.

How to working with treepicker in extjs 4.1.1

I try to create treepicker but i can't done with that http://jsfiddle.net/UKFVd/
Here is my code
var Panel = Ext.create('Ext.panel.Panel', {
bodyPadding: 5,
width: 300,
height: 100,
title: 'Filters',
items: [ {
xtype: 'treepicker',
name: 'list_id',
fieldLabel: 'Task List',
labelWidth: 60,
displayField: 'text',
store: store
}],
renderTo: Ext.getBody()
});
i check error is TypeError: k is undefined How to working with treepicker thanks
You need to include:
Ext.ux.TreePicker
if you have not.
The code in the fiddle you posted is perfectly fine, however, on the left side under External Resources, add the full URL path to TreePicker.js, and try again, and it will work.
Here is a working fiddle rev: http://jsfiddle.net/UKFVd/6/
Tree picker is not an out of box component that ships with extjs, you have to add it to your web page as an additional resource.
here is a page showing examples:
http://extjs.dariofilkovic.com/

Calling UserDefined Functions in ExtJs

I am new to ExtJs,i have designed an entry form as follows,
var HouseForm = new Ext.FormPanel({
renderTo: "HouseCreation",
frame: true,
url: url+'/lochweb/loch/house/persist',
title: 'Create House',
bodyStyle: 'padding:5px',
width: 500,
items: [{
xtype: 'textfield',
fieldLabel: 'Name',
name: 'name',
allowBlank:false
},{
xtype: 'textfield',
fieldLabel: 'TaxId',
name: 'taxId',
allowBlank:true
}
});
var win = new Ext.Window({
layout:'fit',
closable: false,
resizable: true,
plain: true,
border: false,
items: [HouseForm]
});
win.show();
});
I need to validate the user inputs manually,so i need to call my function to validate the user inputs.how to define and call a function and also is there any other layout other than fit?
Thanks
You can simply write your functions/methods in same .js file and call them as usual i.e. () . It will work.
About layouts, there many varieties of layouts available in ExtJS. Here is the link which shows example and minimal code of all the layouts possible in ExtJS.

Extjs Cloning a panel

panel({}) and all its contents like grid, form and want to render that exact clone to another panel is there a way to do it..is it possible to do it with panel.getEl() or is there any other way...please help
The sra's answer is incorrect. Ext's cloneConfig does exactly what you want it to. http://docs.sencha.com/ext-js/4-1/#!/api/Ext.Component-method-cloneConfig
The following code renders two of the "same" panels to the body.
var panel = Ext.create('Ext.Panel', {
width: 500,
height: 300,
title: "HBoxLayout Panel",
layout: {
type: 'hbox',
align: 'stretch'
},
renderTo: document.body,
items: [{
xtype: 'panel',
title: 'Inner Panel One',
flex: 2
},{
xtype: 'panel',
title: 'Inner Panel Two',
flex: 1
},{
xtype: 'panel',
title: 'Inner Panel Three',
flex: 1
}]
});
var clone = panel.cloneConfig();
I must admit that the old answer was not entirely correct. Cloning of Componments is available since ExtJS2 and can be done via cloneConfig(overrides) which is a instance-method.
This will return a clone of the current instance with the applied overrides (if set). A clean clone will require you to use correct configurations, meaning no instances are created within the config. Here are some information bout this For more details read the Sencha guides
Old answer (only valid if the components to clone configs contains instances instead of plain configurations)
No, there is no buildin way to do this. And you should not try it. Consider to wrap the panel in a function that returns a instance of it (a simple sort of factory).
Edit
Something like this:
Factory.Panel = function (config) {
var defaults = {
labelWidth: 80,
labelAlign: 'left',
layout: 'form',
width: 720,
autoHeight: true,
header: false,
bodyStyle: 'padding:10px 15px;'
};
var cfg = Ext.apply({}, config, defaults);
var cmp = new Panel(cfg);
return cmp;
}
You can add as much function params as you like. This would be a clean way to do it. You just can clone simple object like a record. Note that Factory is a Namespace!

Resources