I am using the file uploader in extjs 'fileuploadfield' (Ext.form.field.File), and in my button handler I would like to upload it as base64
handler: function(){
if(self.getForm().isValid()){
self.getForm().submit({
url: myURL,
headers: {
'Accept': 'application/json; charset=utf-8'
},
I would like something like this :
handler: function(){
if(self.getForm().isValid()){
var f = self.getForm().getFileStream();
var base64 = convertToBase64(f);
var params = {};
params.base64 = base64;
Ext.Ajax.request({
params: params,
scope: this,
url: myURL,
method: 'POST',
callback: function (options, success, response) {
}
)
}
Where would I get the file data from the form object? What can I used to convert to base64? Does my logic seem correct in how I am approaching this problem?
Please try this.
Ext.onReady(function() {
Ext.create('Ext.form.field.File', {
id: 'uploadFile',
renderTo: 'example-form',
emptyText: 'Select a file to upload...',
fieldLabel: 'File upload',
labelAlign: 'right',
labelSeparator: ' ',
buttonText: 'Select file...',
labelWidth: 107,
padding: '3 0 0 20',
width: 400,
listeners: {
'change': function(fileUploadComponent, value, eOpts) {
this.onFileChange(fileUploadComponent, value, eOpts);
}
},
onFileChange: function(fileUploadComponent, value, eOpts) {
var file = Ext.getCmp('uploadFile').getEl().down('input[type=file]').dom.files[0];
if (file != null) {
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onloadend = function(oFREvent) {
var byteArray= new Uint8Array(oFREvent.target.result);
var len = byteArray.byteLength;
var binary = '';
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(byteArray[i]);
}
byteArray= window.btoa(binary);
alert(byteArray);
}
}
}
});
});
Java code to convert this in InputStream :
public InputStream persistFile(String imageByteArray){
byte[] byteArray = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.decode(imageByteArray);
InputStream is = new ByteArrayInputStream(byteArray);
return is;
}
Here is fiddle