Java / Struts - File Upload (csv as zip) , Save , Unzip & Rename

Thursday, July 23, 2015 Unknown 0 Comments

This is simple file upload example with Struts and Java.
You can find the sample project at end of the tutorial.

First I have to describe the requirements.
  1. We need to upload the csv file as a zip file.
  2. We Need to save and unzip the zip file .
  3. Get the csv file and rename
According to the requirement the csv file size is more than 100Mb.
For that reason user need to zip the file and it help's to reduse the file size.
For example if original csv file size is 350Mb, after zip it is around 65Mb so its easy to upload with less bandwidth (:)).
First you need to create project using Maven(You can find the sample project at end of the tutorial).
struts.xml


   
My index.jsp redirected to upload.Action so it is return the UploadFile.jsp
   

In here my Action class is UploadFileAction and it contains uploadFile methaod that contains the file uploading functionality.
I have use the file saving location as struts parameter (filesPath) and it will be directly accessed by the action class using getters and setters.

I have use to struts intercepter for validate the file size and define the maximum file size.


Also that intercepter use to allowed only zip files. That means user can only upload the zip files they can't upload other file types.

  
This execAndWait intercepter do the important job here.
When you uploading large size of file it getting long time to upload(it will depends on you internet connection).

Apache Struts 2 Documentation Say's
Source : https://struts.apache.org/docs/execute-and-wait-interceptor.html

Execute and Wait Interceptor


The ExecuteAndWaitInterceptor is great for running long-lived actions in the background while showing the user a nice progress meter.
This also prevents the HTTP request from timing out when the action takes more than 5 or 10 minutes.
This interceptor also supports using an initial wait delay.

Here I use delay and it is optional (delay - an initial delay in millis to wait before the wait page is shown (returning wait as result code))
Until file upload success, reloading the uploadDataWait page by Execute and Wait Interceptor.

   
uploadFile method in UploadFileAction is calling three methds in FilesUtill class.

After successful upload the zip file and extracted csv file can find the given location. Also user redirected to UploadFileSuccess page.




For more details you can use given working sample source codes.

Download

0 comments: