Previously I posted an example on how to download multiple images or files using DotNetZip library
here.
Today I will explain how we can use the same library to unzip images from a zipped folder and insert them into an SQL Server table.
Note: I have used NeatUpload library developed by Dean Brettle to display import progress to the user which can be found
here. If you don’t want to use it, remove the namespace from the code and modify the code to not use NeatUpload controls.
Libraries used:
Here is the piece of code:
using System;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Data.OleDb;
using System.IO;
/* Other NameSpaces*/
using Ionic.Utils.Zip;
using Brettle.Web.NeatUpload;
public partial class Admin_Photos_aspx : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Add triggers to ProgressBar1 (optional)
ProgressBar1.AddTrigger(uxZipImport);
ProgressBar1.AddTrigger((ImageButton)FormView1.FindControl("AddNewPhotoButton"));
}
protected void DeleteFiles(string folderName)
{
string folderPath = folderName;
string[] files = Directory.GetFiles(folderPath);
foreach (string fileName in files)
{
File.Delete(fileName);
}
}
protected void uxZipImport_Click(object sender, ImageClickEventArgs e)
{
string rootFolderPath = "C:/Inetpub/Temporary/FriendUpload";
// Create Temporary User directory to store images
DirectoryInfo di = CreateUserDirectory(rootFolderPath);
string serverFilePath = di.FullName + @"\" + FileUpload1.FileName;
if (FileUpload1.HasFile && FileUpload1.ContentLength > 0)
{
// Store uploaded zip file in User folder in FriendUpload folder
// NeatUpload requires you to move the file to a permanent location
// Uncomment the following FileUpload1.SaveAs and comment FileUpload1.MoveTo if you don’t want to use NeatUpload
//FileUpload1.SaveAs(serverFilePath);
FileUpload1.MoveTo(Path.Combine(di.FullName, FileUpload1.FileName), Brettle.Web.NeatUpload.MoveToOptions.Overwrite);
}
else
{
return;
}
// Get the path of zipped file to unpack
string ZipToUnpack = serverFilePath;
// Where to unpack
string TargetDir = di.FullName;
string extractedFolderName = "";
using (ZipFile zip1 = ZipFile.Read(ZipToUnpack))
{
// here, we extract every entry, but we could extract
// based on entry name, size, date, etc.
foreach (var entry in zip1)
{
entry.Extract(TargetDir, true);
// Get the extracted file name, this can include folder name also
string extractedFileName = entry.FileName;
// remove file name to get the folder name
if (entry.FileName.Contains("/"))
{
extractedFolderName = extractedFileName.Remove(extractedFileName.LastIndexOf("/"));
}
else
{
extractedFolderName = "";
}
}
}
DirectoryInfo d;
if (string.IsNullOrEmpty(extractedFolderName))
{
d = new DirectoryInfo(TargetDir);
}
else
{
d = new DirectoryInfo(TargetDir + @"/" + extractedFolderName);
}
int count = 0;
// ProgressInfo (optional)
ProgressInfo progress = ProgressBar1.ProcessingProgress = new ProgressInfo(d.GetFiles("*.jpg", SearchOption.TopDirectoryOnly).Length, "Images");
foreach (FileInfo f in d.GetFiles("*.jpg"))
{
using (FileStream fileStream = f.OpenRead())
{
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, (int)fileStream.Length);
PhotoManager.AddPhoto(Convert.ToInt32(Request.QueryString["AlbumID"]), f.Name, buffer);
}
// Displaying the number of images processed to the user
count++;
progress.Value = count;
}
progress.Text = "Import complete.";
GridView1.DataBind();
// Delete temporary files after processing (optional)
di.Delete(true);
}
/* Create temporary User Directory to store images and zipped file. */
public DirectoryInfo CreateUserDirectory(string directoryPath)
{
string userName = System.Guid.NewGuid().ToString("N");
if (!string.IsNullOrEmpty(User.Identity.Name))
{
userName = User.Identity.Name;
}
string userDirectoryName = directoryPath + "\\" + userName;
DirectoryInfo di;
if (!Directory.Exists(userDirectoryName))
{
di = System.IO.Directory.CreateDirectory(userDirectoryName);
return di;
}
else
{
di = new DirectoryInfo(userDirectoryName);
}
return di;
}
}
/* PhotoManager.AddPhoto method */
public static void AddPhoto(int AlbumID, string Caption, byte[] BytesOriginal) {
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString)) {
using (SqlCommand command = new SqlCommand("AddPhoto", connection)) {
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@AlbumID", AlbumID));
command.Parameters.Add(new SqlParameter("@Caption", Caption));
command.Parameters.Add(new SqlParameter("@BytesOriginal", BytesOriginal));
command.Parameters.Add(new SqlParameter("@BytesFull", ResizeImageFile(BytesOriginal, 600)));
command.Parameters.Add(new SqlParameter("@BytesPoster", ResizeImageFile(BytesOriginal, 198)));
command.Parameters.Add(new SqlParameter("@BytesThumb", ResizeImageFile(BytesOriginal, 100)));
connection.Open();
command.ExecuteNonQuery();
}
}
}
// Helper Functions
private static byte[] ResizeImageFile(byte[] imageFile, int targetSize) {
using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile))) {
Size newSize = CalculateDimensions(oldImage.Size, targetSize);
using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb)) {
using (Graphics canvas = Graphics.FromImage(newImage)) {
canvas.SmoothingMode = SmoothingMode.AntiAlias;
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));
MemoryStream m = new MemoryStream();
newImage.Save(m, ImageFormat.Jpeg);
return m.GetBuffer();
}
}
}
}
/* Stored procedure AddPhoto */
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[AddPhoto]
@AlbumID int,
@Caption nvarchar(50),
@BytesOriginal image,
@BytesFull image,
@BytesPoster image,
@BytesThumb image
AS
INSERT INTO [Photos] (
[AlbumID],
[BytesOriginal],
[Caption],
[BytesFull],
[BytesPoster],
[BytesThumb] )
VALUES (
@AlbumID,
@BytesOriginal,
@Caption,
@BytesFull,
@BytesPoster,
@BytesThumb )
RETURN