Search code examples
javascripthtmlfile-uploadsapui5

Upload, read, write and download HTML file in SAPUI5 application


I would like to create a SAPUI5 application in which an HTML file can be uploaded. The contents of the file should be read in the next step. After the header tag, an additional text will be inserted in the content and the new file will be made available for download. To make it more clear:

  1. Upload existing HTML file
  2. Edit HTML file with additional text
  3. Make edited HTML file available for download

Any ideas?


Solution

  • It is fairly easy to do this with pure UI5, without needing to use something like WebIDE.

    You need to use three classes in particular:

    Assuming that you don't want to do a backend round-trip for reading the file, you can also use the FileReader API.

    So these are the steps that you need to make:

    1. Add a file uploader in your view:
    <u:FileUploader change="onChangeFile" />
    
    1. Create a handler in the controller for reading the file:
    onChangeFile: function(oEvent) {
        var oModel = this.getView().getModel();
        var oReader = new FileReader();
        oReader.onload = function() {
            oModel.setProperty("/code", oReader.result);
        }
        oReader.readAsText(oEvent.getParameter("files")[0]);
    },
    
    1. Add the code editor control and a download button:
    <Button text="Download" press="onDownload" />
    <ce:CodeEditor type="html" value="{/code}" height="300px" />
    
    1. Create a handler for doing the download itself:
    onDownload: function() {
        var sText = this.getView().getModel().getProperty("/code");
        File.save(sText, "download", "html");
    }
    

    You can find a working fiddle of this here: https://jsfiddle.net/5z7deeyd/1/.


    Later edit:

    If you just need to change the file without user interaction, then you only need steps 1 and 2. For step 2, the handler can look like this:

    onChangeFile: function(oEvent) {
        var oModel = this.getView().getModel();
        var oReader = new FileReader();
        oReader.onload = function() {
            // do something with the oReader.result...
            var sNewContent = oReader.result + "something";
            File.save(sNewContent, "download", "html");
        }
        oReader.readAsText(oEvent.getParameter("files")[0]);
    }