I am currently working on an ASP.Net web project, which allows client to download a well structured submission package. Due to security reason, web server can not create folder and write file on client side. Web server can generate a well structured zipped file and push to the client.
There could be two ways to achieve that;
Fist way:
- Create folders and copy files into each folder
- Use 3rd party tool, eg winrar, 7zip to zip the whole folder to one zipped file
- Send back download web address, and let client download the zipped file
If the zipped file is small and web server is powerful enough, client won’t feel any delay. However if the file is big, client side will get no any response until zip file is ready. We can put similar message, eg “Please wait… ”. But client side still don’t know how long would take. If zip file is not ready within time out period, server will get reset. This is a really awful user experience.
Second way:
- Create folder and zip the files on the fly (on web server’s memory)
- Send back zipped stream to client through Response
- Client download zipping file one by one
Client can clearly feel the progress of downloading.
Here is the code for 2nd solution:
//prepare response header
Response.Clear();
//set Response Content Type
Response.ContentType = "application/x-zip-compressed";
Response.AddHeader("Content-Disposition", "attachment; filename=Download.zip");
ZipOutputStream zipOutput = new ZipOutputStream(Response.OutputStream);
try
{
zipOutput.IsStreamOwner = false;
//set compress level
zipOutput.SetLevel(9);
ArrayList fileList = functions.GetFileList();
foreach (string fileName in fileList)
{
string folderName = "folder1" + @"";
zipEntry = new ZipEntry(folderName + fileName);
zipOutput.PutNextEntry(zipEntry);
byte[] file = functions.GetFile(fileName);
//zip file
zipOutput.Write(file, 0, file.Length);
//send to client for downloading
Response.Flush();
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
finally
{
zipOutput.Finish();
zipOutput.Close();
Response.End();
}