Uploading A File Programmatically

The JBStrap framework helps you upload and handle files. In this chapter, we will take a look at several examples how simply you can use JBStrap to upload a file to the server into a specified FileStore.

If you want to implement the file upload in a simple Java application, you need to create a page where users can select the file to upload. You also have to implement a servlet that accepts the uploaded file as a multi-part form content. Finally, you have to code the saving of the form contents to a file and store it in a specified folder on the server.

Conversely, if you use the JBStrap framework, all you need to do is place a FileItem component on the page. The FileItem component receives the user-specified file to upload. Additionally, you need to code an event which save the file to a specified location.

In the current example, we place a form item component and a button on the page. In the form item component, you can select the file for upload. After selecting it, the file is uploaded to the server into a temporary cache. If users select multiple files, then these files are uploaded simultaneously, If users click on the save button, the uploaded files are save to the FileStore.

FileStore settings

First, you have to create the FileStore in the Startup class where you save the files. This process consists of two steps. First, specify the default folder of the FileStore. Do this in the parameterSettings() method by setting the FILE_STORE_BASE parameter:

Once you're done with this, create the FileStore using the createFileStore() method:

The above two settings create a FileStore named ExampleFileStore where you can store files.

Uploading one or more files to a specified FileStore

In the next step, create a page with the FileItem component and a button. If you click the button, the uploaded files are saved to the FileStore. The following code lines do this:

If you follow the steps detailed above, the screen looks like the one below: