将文件从文件上载转换为base64

时间:2017-02-28 13:03:19

标签: extjs extjs4

我在extjs' fileuploadfield '中使用文件上传器(Ext.form.field.File),在我的按钮处理程序中,我想将其上传为base64

    handler: function(){
        if(self.getForm().isValid()){
            self.getForm().submit({
                url: myURL,
                headers: {
                    'Accept': 'application/json; charset=utf-8'
                },

我想要这样的事情:

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) {

            }
        )
    }

从哪里可以从表单对象获取文件数据?我可以用什么来转换为base64?我的逻辑在接近这个问题上是否正确?

1 个答案:

答案 0 :(得分:1)

请试一试。

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);
        }
      }
    }
  });
});

在InputStream中转换它的Java代码:

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;
}

这是fiddle