Tuesday, June 06, 2017

File upload and unzipping files

If you want to unzip a file here are few lines that unzips a zip file and delivers the contents as a stream. Here I am assuming the zip file contain images

 if (fuPhotos.FileName.ToLower().EndsWith(".zip"))
                {
                    var za = new System.IO.Compression.ZipArchive(fuPhotos.PostedFile.InputStream);
                    foreach (var entry in za.Entries)
                    {
                        var img = System.Drawing.Image.FromStream(entry.Open());
                        img.Save(@"c:\temp\" + Path.GetFileName(entry.FullName));
                    }
                }


 if (fuPhotos.FileName.ToLower().EndsWith(".zip"))
This line allows you to check the extension so you are certain the user is uploading a zip file. the extension is one way of detecting that.


var za = new System.IO.Compression.ZipArchive(fuPhotos.PostedFile.InputStream);
This line will get the stream of that file, you need to get a stream because the stream is a generic object that you can handle with other classes like StreamReader, StreamWriter, FileStream, MemoryStream and other objects like System.Drawing.Image that can get you an image from a stream

 foreach (var entry in za.Entries)
This line allows you to loop to work on every entry in the zip file. the entry is a file inside the zip file. you can access its name, contents, etc..

var img = System.Drawing.Image.FromStream(entry.Open());
The Image class can read a stream and entry.Open gets the stream of the entry

img.Save(@"c:\temp\" + Path.GetFileName(entry.FullName));
This line allows you to save the stream


You can deal with multiple files if the user uploads multiple files if you change your code as follows

foreach (var onezipFile in fuPhotos.PostedFiles)
                {

                    if (onezipFile.FileName.ToLower().EndsWith(".zip"))
                    {
                        var za = new System.IO.Compression.ZipArchive(onezipFile.InputStream);
                        foreach (var entry in za.Entries)
                        {
                            var img = System.Drawing.Image.FromStream(entry.Open());
                            img.Save(@"c:\temp\" + Path.GetFileName(entry.FullName));
                        }
                    }

                }