Advertisement
danieleteti

DMVCFramework :: Uploading multiple files

May 6th, 2024
1,242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 1.57 KB | Source Code | 0 0
  1. // Client
  2.  
  3. procedure TMainForm.UploadFiles(const Files: TArray<String>);
  4. begin
  5.   var lClient: IMVCRESTClient := TMVCRESTClient.Create;
  6.   for var I := 1 to Length(Files) do
  7.   begin
  8.     lClient.AddFile('file' + I.ToString, Files[I-1], TMVCMediaType.APPLICATION_OCTET_STREAM);
  9.   end;
  10.   var lResp := lClient.Execute(httpPOST, ServerBaseURL + '/files');
  11.   if not lResp.Success then
  12.   begin
  13.     ShowMessage(lResp.Content);
  14.   end;
  15. end;
  16.  
  17. // Server
  18. function TFilesController.UploadFile: IMVCResponse;
  19. var
  20.   lFName: String;
  21. begin
  22.   for var I := 0 to Context.Request.Files.Count - 1 do
  23.   begin
  24.     lFName := TPath.GetFileName(Context.Request.Files[I].FileName.Trim(['"']));
  25.     if not TPath.HasValidFileNameChars(lFName, false) then
  26.     begin
  27.       raise EMVCException.Create
  28.         (HTTP_STATUS.BadRequest, lFName + ' is not a valid filename for the hosting OS');
  29.     end;
  30.     TDirectory.CreateDirectory(GetUploadFolder);
  31.     var lAbsoluteFileName := TPath.GetFullPath(TPath.Combine(GetUploadFolder, lFName));
  32.     if TFile.Exists(lAbsoluteFileName) then
  33.     begin
  34.       try
  35.         TFile.Delete(lAbsoluteFileName);
  36.       except
  37.         on E: Exception do
  38.         begin
  39.           raise EMVCException.Create
  40.             (HTTP_STATUS.BadRequest, lFName + ' already present, cannot override - ' + E.Message);
  41.         end;
  42.       end;
  43.     end;
  44.     LogI('Uploading ' + lFName);
  45.     var lFile := TFile.Create(lAbsoluteFileName);
  46.     try
  47.       lFile.CopyFrom(Context.Request.Files[I].Stream, 0);
  48.     finally
  49.       lFile.free;
  50.     end;
  51.   end;
  52.   Result := OKResponse();
  53. end;
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement