Scout/HowTo/3.8/Transfer a file from the client to the server

From Eclipsepedia

< Scout‎ | HowTo‎ | 3.8
Jump to: navigation, search

This tutorial describes how to transfer a file from the client to the server by using RemoteFile.

Contents

Create the Form

  1. Create a new form (name: UploadFileForm, no form id, no modify handler, no permissions).
  2. Add a new file chooser field to the main box (name: FileField).
  3. In Scout Object Properties view, choose Type Load and Mandatory in Behavior for the newly created field.
  4. Add a new variable named RemoteFile (Bean type RemoteFile) to the form.

Add File Upload Code

Overwrite execStore of the NewHandler as follows:

File file = getFileField().getValueAsFile();
String name = IOUtility.getFileName(file.getAbsolutePath());
String fileExtension = IOUtility.getFileExtension(name);
try {
  RemoteFile remoteFile = new RemoteFile(name, System.currentTimeMillis());
  remoteFile.readData(new FileInputStream(file));
  remoteFile.setContentLength((int) file.length());
  remoteFile.setContentTypeByExtension(fileExtension);
  setRemoteFile(remoteFile);
}
catch (IOException e) {
  throw new ProcessingException("Could not remote file", e);
}
 
IUploadFileProcessService service = SERVICES.getService(IUploadFileProcessService.class);
UploadFileFormData formData = new UploadFileFormData();
exportFormData(formData);
formData = service.create(formData);

Add Menu to Open Form

  1. Add a new sub menu to the Desktop / FileMenu (name UploadFileMenu).
  2. Overwrite execInitAction() of the new menu as follows:
UploadFileForm form = new UploadFileForm();
form.startNew();
form.waitFor();

Server Side Handling

Use the following code in the create method of the UploadFileProcessService:

try {
  // get content from remote file
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  formData.getRemoteFile().writeData(bos);
  bos.flush();
  byte[] content = bos.toByteArray();
 
  int updated = SQL.update("" +
      " UPDATE FILES " +
      "    SET CONTENT = :content " +
      "  WHERE FILENAME = :filename "
      , new NVPair("filename", formData.getRemoteFile().getName())
      , new NVPair("content", content)
      );
 
  if (updated == 0) {
    SQL.insert("" +
        " INSERT INTO FILES " +
        "    (FILENAME, CONTENT) " +
        "   VALUES " +
        "    (:filename, :content) "
        , new NVPair("filename", formData.getRemoteFile().getName())
        , new NVPair("content", content)
        );
  }
}
catch (IOException e) {
  throw new ProcessingException("Could not persist remote file.", e);
}
return formData;

Alternatively you can store the RemoteFile on the server disk:

RemoteFile remote = formData.getRemoteFile();
SERVICES.getService(IRemoteFileService.class).putRemoteFile(remote);

Now you are able to open the new form via the menu, choose a file to upload, and handle the file content on server side.

References

Forum post 497216