10/21/2014

[ExtJS] Remove Fake Path in File Field Across Browsers

Here's an example for file uploader with Ext JS. Whenever users pick a file, the file field will fire a change event with the arguments (field, value).
Ext.create('Ext.form.Panel', {
    title: 'Upload a Photo',
    width: 400,
    bodyPadding: 10,
    frame: true,
    renderTo: Ext.getBody(),
    items: [{
        xtype: 'filefield',
        listeners: {
            change: function(field, value) {
                console.log('value', value);
            }
        }
    }]
});
According to the document, 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.
For example, in Chrome, the output in the snippet above is:
value C:\fakepath\myfile.txt 
The same code in Firefox will print:
value myfile.txt 
How if we just get want to get the file name instead of the fake path across browsers? That is, we intend to have the following output in all browsers.
value myfile.txt 
All you have to do is just override the filefield class with the following code.
In Ext JS 5,
Ext.define('Ext.enhance.form.field.File', {
    override: 'Ext.form.field.File',     
    onFileChange: function(button, e, value) {
        this.duringFileSelect = true;
        Ext.form.field.File.superclass.setValue.call(this, value.replace(/^.*(\\|\/|\:)/, ''));
        delete this.duringFileSelect;
    }   
});
In Ext JS 4,
Ext.define('Ext.enhance.form.field.File', {
    override: 'Ext.form.field.File',
    onFileChange: function() {
        this.lastValue = null;
        Ext.form.field.File.superclass.setValue.call(this, this.fileInputEl.dom.value.replace(/^.*(\\|\/|\:)/, ''));
   }
});
Please use Chrome to test this overriding in the fiddle.