Sometimes in a web site you might need the user to upload a zipped file for space issues but the user can’t or doesn’t know how. You might want to conserve space on the server if you have a lot of images. This is also a good way to keep Google from indexing your images from their search. In another article I will show you how to unzip or uncompress but today here is how you can zip an uploaded file. I found a similar article but it was in c#.
As always you need to create a new web application project in Visual Studio and name the project ‘UploadNZip’. Then add a form and add a web reference to iconic.dll. You can get the file from here.
Add the following code to the page.
<form id="form1" runat="server">
<asp:FileUpload ID="file2Upload" runat="server" />
<asp:Button ID="btnZipFile" Text="ZipFile" runat="server" OnClick="btnZipFile_Click" />
<asp:Label ID="lblStatus" runat="server" ForeColor="Red" />
In the code behind of this form add the following code.
Protected Sub btnZipFile_Click(sender As Object, e As EventArgs) Handles btnZipFile.Click
‘Zip a File after uploading
If file2Upload.HasFile Then
‘Store the directory for the Zipped File
Dim CurrentPath As String = Server.MapPath("~/ZipFiles/")
‘Get the variables to save the file first to the location
Dim curpath As String = CurrentPath & Path.GetFileName(file2Upload.PostedFile.FileName)
Dim filenames As String() = Directory.GetFiles(CurrentPath)
‘As files to the zipped file. This would be one file for this example but could be more
Using zip As New Ionic.Zip.ZipFile()
Dim [date] As String = DateTime.Now.ToString("d")
[date] = [date].Replace("/", "")
zip.Save(CurrentPath & [date] & ".zip")
lblStatus.Text = "File Added Successfully"
If lblStatus.Text = "File Added Successfully" Then
‘Removes the non-zipped file from the folder
Note: See the comments in the code for better understanding
That’s it. It is very simple to implement and can save a lot of space depending on the files you are trying to compress. This library can also allow you to add password protection to the files you compress. A great way to store files that need protection. One scenario would be if someone paid for a document you can then allow them to get the file, enter the password and track how many times this is done.
Looking for quality web hosting? Look no further than Arvixe Web Hosting!