Load stream file into a form with submit without reloading the page

Hello guys,

I'm having a problem on a sign-up screen, what happens is that this screen is not reloaded after clicking save, and that's where the problem arises, on that screen it is possible to upload images, but as everything is loaded with submit, the record would have to be updated so I had all the information, which does not happen.

With this I'm trying to find a way to get the information from the file loaded in the "file" component to get the data in "% request.MimeData".

The only way I've found it so far has been to reload the whole page, but that's all I do not want to do.

This page has two forms.

Here's a trick of the code.

 

<form style="text-align:left" name="form2" enctype="multipart/form-data" method="post" action="../lists/ss311.csp?OBJID=#(OBJID)#&edita=#(%request.Get("edita"))#" target="listaimagem">
            <input name="txtimg" type="file" size="10" maxlength="200" id="txtimg">
            <input name="addImagem" id="addImagem" type="submit" value="Adicionar" class="botaoconfirmar">
            &nbsp;&nbsp;
            <span id="aguarde" name="aguarde" style="position:absolute"></span>
        </form>

Answers

  1. <html>
    <body>
    <script language="cache" runat="server">
     if %request.ContentType="multipart/form-data" {
      stream=%request.MimeData("oFile1",1)
      file=##class(%Stream.FileBinary).%New()
      file.Filename="c:\InterSystems\"_##class(%File).GetFilename(stream.FileName)
      file.CopyFromAndSave(stream)
     }
    </script>
    <br>
    <FORM NAME="oForm" ENCTYPE="multipart/form-data" METHOD="post">
    <INPUT TYPE="file" NAME="oFile1"/>
    <INPUT TYPE="submit" VALUE="Upload File">
    </FORM>
    </body>
    </html>
  2. <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1, user-scalable=no"/>
    
        <title>Uploading a file from the client to the server without reloading the page</title>
    
        <script type="text/javascript" src="jquery.min.js"></script>
        <script type="text/javascript" src="js/vendor/jquery.ui.widget.js"></script>
        <script type="text/javascript" src="js/jquery.iframe-transport.js"></script>
        <script type="text/javascript" src="js/jquery.fileupload.js"></script>
        <script type="text/javascript">
        $(function(){
          $('#fileupload').fileupload();
        });
        
      </script>
        <script language="cache" runat="server">
          if (%request.IsDefinedMimeData("files[]",1) ) {
            
            stream=%request.GetMimeData("files[]")
            
            file=##class(%Stream.FileBinary).%New()
            file.Filename="c:\InterSystems\"_stream.FileName
            d file.CopyFromAndSave(stream)
          }
    
        </script>
      </head>
    
      <body>
        #($H)#<input id="fileupload" type="file" name="files[]" data-url="#(%request.PageName)#multiple data-sequential-uploads="false">
      </body>
    </html>
  3. Class dc.fileuploadajax Extends %ZEN.Component.page
    {
    
    XData Contents [ XMLNamespace "http://www.intersystems.com/zen" ]
    {
    <page xmlns="http://www.intersystems.com/zen" title="Uploading a file from the client to the server without reloading the page">
      <group labelPosition="left">
        <text label="Current date/time on the server:" value="#(%this.%Eval($ZDT($H)))#"/>
      </group>
      <form enctype="multipart/form-data" target="upload_target" labelPosition="left">
        <text label="Name:" name="proc"/>
        <fileUpload name="file" label="Select a file:"/>
        <submit caption="Upload"/>
        <iframe name="upload_target" hidden="true"/>
      </form>
      <fieldSet legend="Information about a previously uploaded file" labelPosition="left">
        <text id="proc" label="Name"/>
        <text id="fileSize" label="File size"/>
        <text id="fileName" label="File name"/>
        <button caption="Refresh" onclick="zenPage.GetFileInfo();"/>
      </fieldSet>
    </page>
    }
    
    ClassMethod %OnSubmit(pSubmit As %ZEN.SubmitAs %Status
    {
      #dim %session As %CSP.Session
      #dim stream As %CSP.BinaryStream=pSubmit.%GetStream("file")
    
      if $IsObject(stream{
        set %session.Data("fileSize")=stream.Size
        set %session.Data("fileName")=stream.FileName
      }
      set %session.Data("proc")=pSubmit.%GetValue("proc")
      quit $$$OK
    }
    
    ClassMethod GetFileInfo() [ ZenMethod ]
    {
      &js<
      zenSetProp('proc','value',#(..QuoteJS(%session.Data("proc")))#);
      zenSetProp('fileSize','value',#(..QuoteJS(%session.Data("fileSize")))#);
      zenSetProp('fileName','value',#(..QuoteJS(%session.Data("fileName")))#);
      >
    }
    }

If you want, I can give ZEN-examples of asynchronous uploading of immediately several files using the File API, but this will only work in new browsers.

I am interested in the Zen-examples please. Thanks!

(

  1. Asynchronous uploading only one file

    Class upload.fileOne Extends %ZEN.Component.page
    {
    
    Parameter DOMAIN = "DC";
    
    XData Style
    {
      <style type="text/css">
      </style>
    }
    
    XData Contents [ XMLNamespace "http://www.intersystems.com/zen" ]
    {
    <page xmlns="http://www.intersystems.com/zen" title="Upload file using XMLHttpRequest" labelPosition="left">
      <hgroup cellVAlign="bottom">
        <fileUpload label="Select the file" id="fileToUpload" onchange="zenPage.fileSelected()"/>
        <button caption="Upload" onclick="zenPage.uploadFile();"/>
      </hgroup>
      <label id="fileType" label="Type: "/>
      <label id="fileName" label="Name: "/>
      <label id="fileSize" label="Size: "/>
      <html>
        <div id="progressNumber">%</div>
        <progress id="progressValue" value="0" max="100.0"></progress>
      </html>
    </page>
    }
    
    ClientMethod uploadFile() [ Language = javascript ]
    {
      var fd new FormData();
      fd.append('fUpload', zen('fileToUpload').findElement('control').files[0]);
      var xhr new XMLHttpRequest();
      xhr.upload.addEventListener('progress'this.uploadProgress, false);
      xhr.addEventListener('load'this.uploadComplete, false);
      xhr.addEventListener('error'this.uploadFailed, false);
      xhr.addEventListener('abort'this.uploadCanceled, false);
      xhr.open('POST''upload.fileOne.cls');
      xhr.send(fd);
    }
    
    ClientMethod uploadProgress(evt) [ Language = javascript ]
    {
      if (evt.lengthComputable) {
        var percentComplete Math.round(evt.loaded * 100 / evt.total);
    
        document.getElementById('progressNumber').innerHTML percentComplete.toString() '%';
        document.getElementById('progressValue').value percentComplete;
      }
      else {
        document.getElementById('progressNumber').innerHTML $$$Text('Cannot compute');
      }
    }
    
    ClientMethod uploadComplete(evt) [ Language = javascript ]
    {
      zenAlert($$$Text('The upload is complete.'));
    }
    
    ClientMethod uploadFailed(evt) [ Language = javascript ]
    {
      zenAlert($$$Text('An error occurred when trying to upload the file.'));
    }
    
    ClientMethod uploadCanceled(evt) [ Language = javascript ]
    {
      zenAlert($$$Text('The upload was canceled by the user or the browser dropped the connection.'));
    }
    
    ClientMethod fileSelected() [ Language = javascript ]
    {
      var file zen('fileToUpload').findElement('control').files[0];
      if (file) {
    
        var fileSize = 0;
        if (file.size > 1024 * 1024)
           fileSize (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() $$$Text('MB');
        else
           fileSize (Math.round(file.size * 100 / 1024/ 100).toString() $$$Text('KB');
    
        zenSetProp('fileType','value',file.type);
        zenSetProp('fileName','value',file.name);
        zenSetProp('fileSize','value',fileSize);
         
      }
    }
    
    ClassMethod %OnPreHTTP() As %Boolean ServerOnly = 1 ]
    {
      #dim %request As %CSP.Request
      #dim stream As %CSP.BinaryStream=%request.GetMimeData("fUpload")
      if $IsObject(stream{
        
        #; here you do with the received file useful work
        
        /*
        set ^tmp("filename")=stream.FileName
        set ^tmp("filesize")=stream.Size
        */
        
        quit $$$NO
      }
      quit $$$YES
    }
    
    }
  2. Asynchronous uploading immediately of several files
    Class upload.fileMany Extends %ZEN.Component.page
    {
    
    Parameter DOMAIN = "DC";
    
    XData Style
    {
    <style type="text/css">
      .ok {
        color:green;
      }
    
      #dropZone {
        width: 360px;
        height: 125px;
        borderdashed 2px #ccc;
        background-color: #fefefe;
        color: #ccc;
        text-aligncenter;
        padding: 125px 0 0 0;
      }
    
    </style>
    }
    
    XData Contents [ XMLNamespace "http://www.intersystems.com/zen" ]
    {
    <page xmlns="http://www.intersystems.com/zen" title="Upload immediately multiple files using XMLHttpRequest">
      <html id="dropZone">Drag files here or click below</html>
      <hgroup cellVAlign="bottom">
        <html id="selectFiles" label="Choose the files">
          <input type="file" class="fileUpload" id="fileToUpload" onchange="zenPage.fileSelected(document.getElementById('fileToUpload').files)" multiple="multiple" />
        </html>
        <button caption="Clear" title="Clear the queue" onclick="zenPage.clearList();"/>
        <spacer width="10"/>
        <button caption="Upload" title="Upload files to the server" onclick="zenPage.uploadFile();"/>
      </hgroup>
      <fieldSet legend="Files waiting to upload">
        <html id="holder"/>
      </fieldSet>
    </page>
    }
    
    ClientMethod clearList() [ Language = javascript ]
    {
      fileQueue=[];
      zen('holder').getEnclosingDiv().innerHTML='';
      zen('selectFiles').refreshContents();
    }
    
    ClientMethod fileSelected(files) [ Language = javascript ]
    {
      var holder zen('holder').getEnclosingDiv();
      for (var = 0; i files.length; i++) {
      
        var file files[i];
    
        var fileSize = 0;
        if (file.size > 1024 * 1024)
          fileSize (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() $$$Text('MB');
        else
          fileSize (Math.round(file.size * 100 / 1024/ 100).toString() $$$Text('KB');
      
        var divInfo document.createElement('div');
        divInfo.innerHTML=file.name+' ('+file.type+') - '+fileSize;
        holder.appendChild(divInfo);
    
        var divProgN document.createElement('div');
        divProgN.id='progressNumber'+i;
        divProgN.innerHTML='%';
        holder.appendChild(divProgN);
    
        var prog document.createElement('progress');
        prog.id='progressValue'+i;
        prog.max='100.0';
        prog.value='0';
        holder.appendChild(prog);
    
        fileQueue.push({i:i,file:file});
      }
    }
    
    ClientMethod uploadFile() [ Language = javascript ]
    {
      while (fileQueue.length > 0) {
        var item=fileQueue.pop();
        uploadFile(item.file,item.i);
      }
    }
    
    ClientMethod onloadHandler() [ Language = javascript ]
    {
      if (typeof FileReader == "undefined") zenAlert($$$Text('Sorry, your browser does not support File API, so this demo will not work correctly'));
      fileQueue new Array();
    
      uploadFile function (file, i) {
        var xhr new XMLHttpRequest(), upload xhr.upload, fd new FormData();
        
        fd.append('fUpload', file);
    
        upload.addEventListener('progress',
        function (evt) {
          if (evt.lengthComputable) {
            var percentComplete Math.round(evt.loaded * 100 / evt.total);
    
            document.getElementById('progressNumber'+i).innerHTML percentComplete.toString() '%';
            document.getElementById('progressValue'+i).value percentComplete;
            
          }
          else {
            document.getElementById('progressNumber'+i).innerHTML $$$Text('Cannot compute');
          }
          
        }, false);
        upload.addEventListener('load'function (ev) {
          var c=document.getElementById('progressNumber'+i);
          c.className='ok';
          c.innerHTML='OK';
        }, false);
        upload.addEventListener('error'function (ev) {zenAlert($$$Text('An error occurred when trying to upload the file.'));}, false);
        upload.addEventListener('abort'function (ev) {zenAlert($$$Text('The upload was canceled by the user or the browser dropped the connection.'));}, false);
        xhr.open('POST','upload.fileMany.cls');
        xhr.setRequestHeader('Cache-Control''no-cache');
        xhr.setRequestHeader('X-Requested-With''XMLHttpRequest');
        xhr.send(fd);
      }
      
      dropZone=zen('dropZone').getEnclosingDiv();
      dropZone.addEventListener('dragenter',  function(ev){
        ev.stopPropagation();
        ev.preventDefault();
      }, false);
      dropZone.addEventListener('dragleave',  function(ev){
        ev.stopPropagation();
        ev.preventDefault();
        this.style['backgroundColor''#FEFEFE';
        this.style['borderColor''#CCC';
        this.style['color''#CCC';
      }, false);
      dropZone.addEventListener('dragover',  function(ev){
        ev.stopPropagation();
        ev.preventDefault();
        this.style['backgroundColor''#F0FCF0';
        this.style['borderColor''#3DD13F';
        this.style['color''#3DD13F';
      }, false);
      dropZone.addEventListener('drop',  function(ev){
      ev.stopPropagation();
      ev.preventDefault();
      this.style['backgroundColor''#FEFEFE';
      this.style['borderColor''#CCC';
      this.style['color''#CCC';
      zenPage.fileSelected(ev.dataTransfer.files);
      }, false);
    }
    
    ClassMethod %OnPreHTTP() As %Boolean ServerOnly = 1 ]
    {
      #dim %request As %CSP.Request
      #dim stream As %CSP.BinaryStream=%request.GetMimeData("fUpload")
      if $IsObject(stream{
        
        #; here you do with the received file useful work
        
        /*
        set ^tmp("filename")=stream.FileName
        set ^tmp("filesize")=stream.Size
        */
        
        quit $$$NO
      }
      quit $$$YES
    }
    
    }

Of course you can do the same on CSP.