Jump to content

Detect cancel OpenDialog in "TUniFileUploadButton"


Luciano França

Recommended Posts


I made a modification in a situation where accessviolation

procedure TMainForm.htmlGetFileAjaxEvent(Sender: TComponent; EventName: string;
  Params: TUniStrings);
var
  aFileName : String;
  aJSONData : String;
  aJsonObj: TJSONObject;
  aFileStream :TFileStream;
  aMemoryStream : TMemoryStream;
  afileType : String;
  aOutputFile : String;


  function getJsonString(wObj: TJSONObject; aItem: String): String;
  var
    aObjItem : TJSONString;
  begin
    aObjItem := wObj.Get(aItem).JsonValue as TJSONString;
    Result := aObjItem.Value;
  end;

  function getJsonStream(wObj: TJSONObject; aItem: String): TMemoryStream;
  var
    aObjItem : TJSONString;
    aBytes : TBytes;
    aString : String;
    i : Integer;
  begin
    aObjItem := wObj.Get(aItem).JsonValue as TJSONString;
    aString := aObjItem.Value;
    i := Pos('base64,', aString);
    if i > 0 then
      aString := Copy(aString, i+7, Length(aString));

    aBytes := TNetEncoding.Base64.DecodeStringToBytes(aString);
    Result := TMemoryStream.Create;
    Result.WriteBuffer(aBytes, Length(aBytes));
  end;

begin
  UniImage1.Picture.Bitmap := nil;
  UniMemo1.Clear;

  if (EventName = 'selected_file') then
  begin
    aJSONData := Params.Values['file_info'];
    aJsonObj := TJSONObject.ParseJSONValue(aJSONData) as TJSONObject;
    try

    If (Not Assigned(aJsonObj)) Or (Not Assigned(aJsonObj.Get('filename'))) Or (Trim(aJsonObj.Get('filename').ToJSON) = Emptystr) Then Begin
     ShowMessage('No file was selected'); 
     Exit;
    End;

      aFileName := getJsonString(aJsonObj, 'filename');
      if aFileName > '' then
      begin
        aOutputFile := UniServerModule.StartPath+'UploadFolder\'+ aFileName;
        aFileType  := getJsonString(aJsonObj, 'filetype');
        aMemoryStream := getJsonStream(aJsonObj, 'filedata');
        try
          aMemoryStream.SaveToFile(aOutputFile);
        finally
          aMemoryStream.free;
        end;

        if Pos('text', aFileType) > 0 then
        begin
          with TStringList.Create do
          try
            LoadFromFile(aOutputFile);
            UniMemo1.Text := Text;
          finally
            free;
          end
        end
        else if Pos('image', aFileType) > 0 then
        begin
          aFileStream := TFileStream.Create(aOutputFile, fmOpenRead);
          try
            UniImage1.LoadFromStream(aFileStream);
          finally
            aFileStream.Free;
          end;
        end
        else if Pos('pdf', aFileType) > 0 then
         ShowMessage('File is PDF')
        else
         ShowMessage('Filetype is unknown')
      end
      else
        ShowMessage('No file was selected');
    finally
      aJsonObj.Free;
    end;
  end;
end;

 

Completing the Topic how to open Simulate automatic Click.

 

Link to comment
Share on other sites

  • 5 months later...
On 10/24/2023 at 12:33 AM, Norm said:

Hi Luciano,

Try the attached project and let me know if that's what you need and I'll supply the source code. It uses port 8077.

 

fuploadDemo.zip 1.91 MB · 2 downloads

 

 Hello, after a long time I came across a problem, if a very large file is chosen, Unigui will crash.
 How could I check the file size and show an Alert to the User.
 

How could I put a file size check in this code below and abort if it is too large.

 With FileHTMLFrame.HTML Do Begin
  Clear;
  Add('<!doctype html>');
  Add('<html>  ');
  Add('  <body>  ');
  Add('    <button id="BtnFileHTMLFrame" style="color:black;font-size:16px;" onclick="selectFile()">Aguarde o envio do Arquivo...</button>');
  Add('    <script> ');
  Add('      async function selectFile() {  ');
  Add('        let file = await fetchFile()  ');
  Add('        let filename, fileData  ');
  Add('        let filetype = ''Unknown'' ');
  Add('        if(file){  ');
  Add('          filename = file.name  ');
  Add('          filetype = file.type  ');
  Add('          let reader = new FileReader(); ');
  Add('          reader.readAsDataURL(file);  ');
  Add('          reader.onload = function() {   ');
  Add('            fileData = reader.result   ');
  Add('            let params = {"filename": filename, "filetype": filetype, "filedata": fileData} ');
  Add('            params= JSON.stringify(params);   ');
  Add('            top.ajaxRequest(top.Form_UploadFileWeb.FileHTMLFrame, ''selected_file'', [''file_info=''+ params]); ');
  Add('          }    ');
  Add('          reader.onerror = function() {   ');
  Add('            let params = {"filename": filename, "filetype": filetype, "filedata": fileData}  ');
  Add('            params= JSON.stringify(params); ');
  Add('            top.ajaxRequest(top.Form_UploadFileWeb.FileHTMLFrame, ''selected_file'', [''file_info=''+ params]); ');
  Add('          }   ');
  Add('        } else {  ');
  Add('          let params = {"filename": filename, "filetype": filetype, "filedata": fileData}  ');
  Add('          params= JSON.stringify(params);   ');
  Add('          top.ajaxRequest(top.Form_UploadFileWeb.FileHTMLFrame, ''selected_file'', [''file_info=''+ params]); ');
  Add('        }   ');
  Add('      }   ');
  Add('      const fetchFile = async () => {   ');
  Add('        return new Promise((resolve, reject) => {  ');
  Add('          const el = document.createElement(''input'');  ');
  Add('          el.type = ''file'';  ');
  Add('          el.style.opacity = ''0'';   ');
  Add('          el.accept =  "' + Ext + '";  ');
  Add('          el.addEventListener(''change'', () => {  ');
  Add('            const file = el.files[0]; ');
  Add('            document.body.removeChild(el);  ');
  Add('            resolve(file);  ');
  Add('          });  ');
  Add('          document.body.appendChild(el); ');
  Add('          el.click();  ');
  Add('          const onFocus = () => { ');
  Add('              window.removeEventListener(''focus'', onFocus); ');
  Add('              document.body.addEventListener(''mousemove'', onMouseMove); ');
  Add('          };   ');
  Add('          const onMouseMove = () => {  ');
  Add('              document.body.removeEventListener(''mousemove'', onMouseMove); ');
  Add('              if (!el.files.length) {  ');
  Add('                  document.body.removeChild(el); ');
  Add('                  resolve(undefined); ');
  Add('              } else { ');
  Add('                resolve(el.files[0]); ');
  Add('              }  ');
  Add('          }   ');
  Add('          window.addEventListener(''focus'', onFocus);  ');
  Add('        }); ');
  Add('      }  ');
  Add('    </script> ');
  Add('  </body> ');
  Add('</html> ');
 End;

 

Link to comment
Share on other sites

1 hour ago, Luciano França said:

 

 Hello, after a long time I came across a problem, if a very large file is chosen, Unigui will crash.
 How could I check the file size and show an Alert to the User.
 

How could I put a file size check in this code below and abort if it is too large.

 With FileHTMLFrame.HTML Do Begin
  Clear;
  Add('<!doctype html>');
  Add('<html>  ');
  Add('  <body>  ');
  Add('    <button id="BtnFileHTMLFrame" style="color:black;font-size:16px;" onclick="selectFile()">Aguarde o envio do Arquivo...</button>');
  Add('    <script> ');
  Add('      async function selectFile() {  ');
  Add('        let file = await fetchFile()  ');
  Add('        let filename, fileData  ');
  Add('        let filetype = ''Unknown'' ');
  Add('        if(file){  ');
  Add('          filename = file.name  ');
  Add('          filetype = file.type  ');
  Add('          let reader = new FileReader(); ');
  Add('          reader.readAsDataURL(file);  ');
  Add('          reader.onload = function() {   ');
  Add('            fileData = reader.result   ');
  Add('            let params = {"filename": filename, "filetype": filetype, "filedata": fileData} ');
  Add('            params= JSON.stringify(params);   ');
  Add('            top.ajaxRequest(top.Form_UploadFileWeb.FileHTMLFrame, ''selected_file'', [''file_info=''+ params]); ');
  Add('          }    ');
  Add('          reader.onerror = function() {   ');
  Add('            let params = {"filename": filename, "filetype": filetype, "filedata": fileData}  ');
  Add('            params= JSON.stringify(params); ');
  Add('            top.ajaxRequest(top.Form_UploadFileWeb.FileHTMLFrame, ''selected_file'', [''file_info=''+ params]); ');
  Add('          }   ');
  Add('        } else {  ');
  Add('          let params = {"filename": filename, "filetype": filetype, "filedata": fileData}  ');
  Add('          params= JSON.stringify(params);   ');
  Add('          top.ajaxRequest(top.Form_UploadFileWeb.FileHTMLFrame, ''selected_file'', [''file_info=''+ params]); ');
  Add('        }   ');
  Add('      }   ');
  Add('      const fetchFile = async () => {   ');
  Add('        return new Promise((resolve, reject) => {  ');
  Add('          const el = document.createElement(''input'');  ');
  Add('          el.type = ''file'';  ');
  Add('          el.style.opacity = ''0'';   ');
  Add('          el.accept =  "' + Ext + '";  ');
  Add('          el.addEventListener(''change'', () => {  ');
  Add('            const file = el.files[0]; ');
  Add('            document.body.removeChild(el);  ');
  Add('            resolve(file);  ');
  Add('          });  ');
  Add('          document.body.appendChild(el); ');
  Add('          el.click();  ');
  Add('          const onFocus = () => { ');
  Add('              window.removeEventListener(''focus'', onFocus); ');
  Add('              document.body.addEventListener(''mousemove'', onMouseMove); ');
  Add('          };   ');
  Add('          const onMouseMove = () => {  ');
  Add('              document.body.removeEventListener(''mousemove'', onMouseMove); ');
  Add('              if (!el.files.length) {  ');
  Add('                  document.body.removeChild(el); ');
  Add('                  resolve(undefined); ');
  Add('              } else { ');
  Add('                resolve(el.files[0]); ');
  Add('              }  ');
  Add('          }   ');
  Add('          window.addEventListener(''focus'', onFocus);  ');
  Add('        }); ');
  Add('      }  ');
  Add('    </script> ');
  Add('  </body> ');
  Add('</html> ');
 End;

 

 

Solution Partial

  Add('          const fsize = file.size; ');
  Add('          const Tamfile = Math.round((fsize / 1024)); ');
  Add('          if (Tamfile >= 8096) { ');
  Add('          alert("Arquivo muito grande escolha um aquivo menor que 8mb"); ');
  Add('          document.body.removeChild(el);  ');
  Add('          resolve(undefined); } ');

how to exchange Alert for MessageDLG in javascript

 

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...