Tuesday, December 8, 2009

Unzip Files and Upload Each File To Server

This method will allow you to unzip a zipped file and upload all the files separately to your server. You will need to import the proper libraries. The directory is the location to place the files after they are unzipped. The location of the zipped file will be contained in the FormFile class.


final static int BUFFER = 2048;
/**
* This method unzips the file and upload the documents to a file directory.
* The path is the Selected FormFile the user selected from the jsp page which is a zip file.
* The directory is the location where the files will be stored.
*
*/
public void uploadWithNameZip(FormFile path,String directory)
{
try {
BufferedOutputStream dest = null;
//Creates a zipinput stream
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(path.getInputStream()));
ZipEntry entry;
while((entry = zis.getNextEntry()) != null) {
int count;
byte data[] = new byte[BUFFER];
//pulls the filename from each in the zip file
String fileName = entry.getName().trim();
//creates the path where file will be stored with filename
String dir = directory.trim();
dir = dir+System.getProperty("file.separator");
String totalName=dir+fileName;
//saves each individual file on the file server
OutputStream fileOut = new FileOutputStream(totalName);
dest = new BufferedOutputStream(fileOut, BUFFER);
while ((count = zis.read(data, 0, BUFFER))!= -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
}
zis.close();
} catch(Exception e) {
e.printStackTrace();
return null;
}
}


0 comments: