Help :: Image Upload Saving Metadata to XML and Search via metadata

Last post 05-09-2008 11:17 AM by NC01. 1 replies.

Sort Posts:

  • Help :: Image Upload Saving Metadata to XML and Search via metadata

    05-09-2008, 3:13 AM
    • Loading...
    • didymus
    • Joined on 05-01-2008, 5:19 AM
    • Posts 2

    Hi, I need some help here. Right now, I'm stuck at this function

    Logic: check if image already existed when uploading, if yes, ask user for input yes/no, if yes overwrite, if no, change a new filename.

    This is my upload.aspx

    1    using System;
    2    using System.IO;
    3    using System.Collections;
    4    using System.ComponentModel;
    5    using System.Data;
    6    using System.Drawing;
    7    using System.Web;
    8    using System.Web.SessionState;
    9    using System.Web.UI;
    10   using System.Web.UI.WebControls;
    11   using System.Web.UI.HtmlControls;
    12   
    13   
    14   namespace netimageupload
    15   {
    16       /// <summary>
    17       /// Summary description for WebForm1.
    18       /// </summary>
    19       public partial class WebForm1 : System.Web.UI.Page
    20       {
    21           // protected System.Web.UI.HtmlControls.HtmlInputFile filUpload;
    22           // protected System.Web.UI.WebControls.Image imgPicture;
    23           // protected System.Web.UI.WebControls.Label lblOutput;
    24           // protected System.Web.UI.WebControls.Button btnUpload;
    25   
    26           private void Page_Load(object sender, System.EventArgs e)
    27           {
    28               // Put user code to initialize the page here
    29           }
    30   
    31           #region Web Form Designer generated code
    32           override protected void OnInit(EventArgs e)
    33           {
    34               //
    35               // CODEGEN: This call is required by the ASP.NET Web Form Designer.
    36               //
    37               InitializeComponent();
    38               base.OnInit(e);
    39           }
    40   
    41           /// <summary>
    42           /// Required method for Designer support - do not modify
    43           /// the contents of this method with the code editor.
    44           /// </summary>
    45           private void InitializeComponent()
    46           {
    47               this.btnUpload.Click += new System.EventHandler(this.btnUpload_Click);
    48               this.Load += new System.EventHandler(this.Page_Load);
    49   
    50           }
    51           #endregion
    52   
    53           private void btnUpload_Click(object sender, System.EventArgs e)
    54           {
    55               // Initialize variables
    56               string sSavePath;
    57               string sThumbExtension;
    58               int intThumbWidth;
    59               int intThumbHeight;
    60   
    61               // Set constant values
    62               sSavePath = "images/Saved Images/";
    63               sThumbExtension = "_thumb";
    64               intThumbWidth = 160;
    65               intThumbHeight = 120;
    66   
    67   
    68   
    69               // If file field isn’t empty
    70               if (filUpload.PostedFile != null)
    71               {
    72                   // Check file size (mustn’t be 0)
    73                   HttpPostedFile myFile = filUpload.PostedFile;
    74                   int nFileLen = myFile.ContentLength;
    75                   if (nFileLen == 0)
    76                   {
    77                       lblOutput.Text = "There wasn't any file uploaded.";
    78                       return;
    79                   }
    80   
    81                   // Check file extension (must be JPG)
    82                   if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
    83                   {
    84                       lblOutput.Text = "The file must have an extension of JPG";
    85                       return;
    86                   }
    87   
    88                   // Read file into a data stream
    89                   byte[] myData = new Byte[nFileLen];
    90                   myFile.InputStream.Read(myData, 0, nFileLen);
    91   
    92                   // Make sure a duplicate file doesn’t exist.  If it does, keep on appending an incremental numeric until it is unique
    93                   string sFilename = System.IO.Path.GetFileName(myFile.FileName);
    94                   string ans;
    95                   int file_append = 0;
    96   
    97                   if (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
    98                   {
    99                       Response.Write("&lt;script type=\"text/javascript\"&gt;var result = confirm('Image already existed. Click OK to overwrite. Click NO for new filename.')</script>");
    100                     
    101                  }
    102  
    103                  // Save the stream to disk
    104                  System.IO.FileStream newFile = new System.IO.FileStream(Server.MapPath(sSavePath + sFilename), System.IO.FileMode.Create);
    105                  newFile.Write(myData, 0, myData.Length);
    106                  newFile.Close();
    107                  TextWriter tw = new StreamWriter(Server.MapPath("Images/Saved Images/" + sFilename + ".html"));
    108  
    109                  // write a line of text to the files
    110                  tw.WriteLine("&lt;html");
    111                  tw.WriteLine("&lt;img src=\"" + sSavePath + sFilename + "\"&gt;" + " " + "&lt;desc=\"" + desc.Text + "\"&gt;" + " " + "&lt;mat=\"" + materials.Text + "\"&gt;" + " " + "&lt;date=\"" + date.Text + "\"&gt;");
    112                  tw.WriteLine("&lt;/html>");
    113  
    114                  // close the stream
    115                  tw.Close();
    116  
    117  
    118                  // Check whether the file is really a JPEG by opening it
    119                  System.Drawing.Image.GetThumbnailImageAbort myCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
    120                  Bitmap myBitmap;
    121                  try
    122                  {
    123                      myBitmap = new Bitmap(Server.MapPath(sSavePath + sFilename));
    124  
    125                      // If jpg file is a jpeg, create a thumbnail filename that is unique.
    126                      file_append = 0;
    127                      string sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + sThumbExtension + ".jpg";
    128                      while (System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile)))
    129                      {
    130                          file_append++;
    131                          sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + file_append.ToString() + sThumbExtension + ".jpg";
    132                      }
    133  
    134                      // Save thumbnail and output it onto the webpage
    135                      System.Drawing.Image myThumbnail = myBitmap.GetThumbnailImage(intThumbWidth, intThumbHeight, myCallBack, IntPtr.Zero);
    136                      myThumbnail.Save(Server.MapPath(sSavePath + sThumbFile));
    137                      imgPicture.ImageUrl = sSavePath + sThumbFile;
    138  
    139  
    140                      // Displaying success information
    141                      lblOutput.Text = "File uploaded successfully!";
    142  
    143  
    144                      // Destroy objects
    145                      myThumbnail.Dispose();
    146                      myBitmap.Dispose();
    147                  }
    148                  catch (ArgumentException errArgument)
    149                  {
    150                      // The file wasn't a valid jpg file
    151                      lblOutput.Text = "The file wasn't a valid jpg file.";
    152                      System.IO.File.Delete(Server.MapPath(sSavePath + sFilename));
    153                  }
    154              }
    155          }
    156  
    157          public bool ThumbnailCallback()
    158          {
    159              return false;
    160          }
    161          protected void btnUpload_Click1(object sender, EventArgs e)
    162          {
    163  
    164          }
    165          protected void txtFName_TextChanged(object sender, EventArgs e)
    166          {
    167  
    168          }
    169          protected void btnUpload_Click2(object sender, EventArgs e)
    170          {
    171  
    172          }
    173  }
    174  }
    175  using System;
    176  using System.IO;
    177  using System.Collections;
    178  using System.ComponentModel;
    179  using System.Data;
    180  using System.Drawing;
    181  using System.Web;
    182  using System.Web.SessionState;
    183  using System.Web.UI;
    184  using System.Web.UI.WebControls;
    185  using System.Web.UI.HtmlControls;
    186  
    187  
    188  namespace netimageupload
    189  {
    190      /// <summary>
    191      /// Summary description for WebForm1.
    192      /// </summary>
    193      public partial class WebForm1 : System.Web.UI.Page
    194      {
    195          // protected System.Web.UI.HtmlControls.HtmlInputFile filUpload;
    196          // protected System.Web.UI.WebControls.Image imgPicture;
    197          // protected System.Web.UI.WebControls.Label lblOutput;
    198          // protected System.Web.UI.WebControls.Button btnUpload;
    199  
    200          private void Page_Load(object sender, System.EventArgs e)
    201          {
    202              // Put user code to initialize the page here
    203          }
    204  
    205          #region Web Form Designer generated code
    206          override protected void OnInit(EventArgs e)
    207          {
    208              //
    209              // CODEGEN: This call is required by the ASP.NET Web Form Designer.
    210              //
    211              InitializeComponent();
    212              base.OnInit(e);
    213          }
    214  
    215          /// <summary>
    216          /// Required method for Designer support - do not modify
    217          /// the contents of this method with the code editor.
    218          /// </summary>
    219          private void InitializeComponent()
    220          {
    221              this.btnUpload.Click += new System.EventHandler(this.btnUpload_Click);
    222              this.Load += new System.EventHandler(this.Page_Load);
    223  
    224          }
    225          #endregion
    226  
    227          private void btnUpload_Click(object sender, System.EventArgs e)
    228          {
    229              // Initialize variables
    230              string sSavePath;
    231              string sThumbExtension;
    232              int intThumbWidth;
    233              int intThumbHeight;
    234  
    235              // Set constant values
    236              sSavePath = "images/Saved Images/";
    237              sThumbExtension = "_thumb";
    238              intThumbWidth = 160;
    239              intThumbHeight = 120;
    240  
    241  
    242  
    243              // If file field isn’t empty
    244              if (filUpload.PostedFile != null)
    245              {
    246                  // Check file size (mustn’t be 0)
    247                  HttpPostedFile myFile = filUpload.PostedFile;
    248                  int nFileLen = myFile.ContentLength;
    249                  if (nFileLen == 0)
    250                  {
    251                      lblOutput.Text = "There wasn't any file uploaded.";
    252                      return;
    253                  }
    254  
    255                  // Check file extension (must be JPG)
    256                  if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
    257                  {
    258                      lblOutput.Text = "The file must have an extension of JPG";
    259                      return;
    260                  }
    261  
    262                  // Read file into a data stream
    263                  byte[] myData = new Byte[nFileLen];
    264                  myFile.InputStream.Read(myData, 0, nFileLen);
    265  
    266                  // Make sure a duplicate file doesn’t exist.  If it does, keep on appending an incremental numeric until it is unique
    267                  string sFilename = System.IO.Path.GetFileName(myFile.FileName);
    268                  string ans;
    269                  int file_append = 0;
    270  
    271                  if (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
    272                  {
    273                      Response.Write("&lt;script type=\"text/javascript\"&gt;var result = confirm('Image already existed. Click OK to overwrite. Click NO for new filename.')</script>");
    274  
    275                  }
    276  
    277                  // Save the stream to disk
    278                  System.IO.FileStream newFile = new System.IO.FileStream(Server.MapPath(sSavePath + sFilename), System.IO.FileMode.Create);
    279                  newFile.Write(myData, 0, myData.Length);
    280                  newFile.Close();
    281                  TextWriter tw = new StreamWriter(Server.MapPath("Images/Saved Images/" + sFilename + ".html"));
    282  
    283                  // write a line of text to the files
    284                  tw.WriteLine("&lt;html");
    285                  tw.WriteLine("&lt;img src=\"" + sSavePath + sFilename + "\"&gt;" + " " + "&lt;desc=\"" + desc.Text + "\"&gt;" + " " + "&lt;mat=\"" + materials.Text + "\"&gt;" + " " + "&lt;date=\"" + date.Text + "\"&gt;");
    286                  tw.WriteLine("&lt;/html>");
    287  
    288                  // close the stream
    289                  tw.Close();
    290  
    291  
    292                  // Check whether the file is really a JPEG by opening it
    293                  System.Drawing.Image.GetThumbnailImageAbort myCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
    294                  Bitmap myBitmap;
    295                  try
    296                  {
    297                      myBitmap = new Bitmap(Server.MapPath(sSavePath + sFilename));
    298  
    299                      // If jpg file is a jpeg, create a thumbnail filename that is unique.
    300                      file_append = 0;
    301                      string sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + sThumbExtension + ".jpg";
    302                      while (System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile)))
    303                      {
    304                          file_append++;
    305                          sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + file_append.ToString() + sThumbExtension + ".jpg";
    306                      }
    307  
    308                      // Save thumbnail and output it onto the webpage
    309                      System.Drawing.Image myThumbnail = myBitmap.GetThumbnailImage(intThumbWidth, intThumbHeight, myCallBack, IntPtr.Zero);
    310                      myThumbnail.Save(Server.MapPath(sSavePath + sThumbFile));
    311                      imgPicture.ImageUrl = sSavePath + sThumbFile;
    312  
    313  
    314                      // Displaying success information
    315                      lblOutput.Text = "File uploaded successfully!";
    316  
    317  
    318                      // Destroy objects
    319                      myThumbnail.Dispose();
    320                      myBitmap.Dispose();
    321                  }
    322                  catch (ArgumentException errArgument)
    323                  {
    324                      // The file wasn't a valid jpg file
    325                      lblOutput.Text = "The file wasn't a valid jpg file.";
    326                      System.IO.File.Delete(Server.MapPath(sSavePath + sFilename));
    327                  }
    328              }
    329          }
    330  
    331          public bool ThumbnailCallback()
    332          {
    333              return false;
    334          }
    335          protected void btnUpload_Click1(object sender, EventArgs e)
    336          {
    337  
    338          }
    339          protected void txtFName_TextChanged(object sender, EventArgs e)
    340          {
    341  
    342          }
    343          protected void btnUpload_Click2(object sender, EventArgs e)
    344          {
    345  
    346          }
    347  }
    348  }
    349  
    

     

     

    97                   if (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
    98                   {
    99                       Response.Write("&lt;script type=\"text/javascript\"&gt;var result = confirm('Image already existed. Click OK to overwrite. Click NO for new filename.')</script>");
    100                    
    101                  }

    is this correct? how do i write if (result == yes) ... etc?

  • Re: Help :: Image Upload Saving Metadata to XML and Search via metadata

    05-09-2008, 11:17 AM
    Answer
    • Loading...
    • NC01
    • Joined on 08-26-2005, 3:33 PM
    • Posts 6,886
    • TrustedFriends-MVPs

    Here is a sample showing how to do that.

    aspx file:

    <form id="Form1" method="post" runat="server">
     Select a file to upload:
     <input type="file" id="fileUploadControl" runat="Server">
     <input type="submit" id="uploadButton" runat="Server" value="Upload..." OnServerClick="uploadButton_Click">
     <br><br>
     <asp:label id="messageArea" runat="server"></asp:label>
    </form>

    aspx.cs file:

    protected string SavedFileName
    {
     get
     {
      object viewState = this.ViewState["SavedFileName"];
      
      return (viewState == null) ? string.Empty : (string)viewState;
     }
     set
     {
      this.ViewState["SavedFileName"] = value;
     }
    }

    protected void uploadButton_Click(Object sender, EventArgs e)
    {
     this.fileUploadControl.PostedFile.FileName

     string uploadFilePath = this.fileUploadControl.PostedFile.FileName;
     string [] filePathArray = uploadFilePath.Split('\\');

     if ( filePathArray.Length <= 0 )
      return;

     string fileName = filePathArray[filePathArray.Length-1];
     string filePath = this.Server.MapPath("Uploads") + "\\" + fileName;
     string tempFilePath = this.Server.MapPath("Temp") + "\\" + fileName;
     bool shouldQueryUser = false;

     try
     {
      if ( System.IO.File.Exists(filePath) )
      {
       shouldQueryUser = true;
       filePath = tempFilePath;
      }

      if ( System.IO.File.Exists(filePath) )   
       System.IO.File.Delete(filePath);

      this.fileUploadControl.PostedFile.SaveAs(filePath);
      this.messageArea.Text = "Successful Upload!<br>";
     }
     catch(Exception ex)
     {
      this.messageArea.Text = "Error saving file: " + fileUploadControl.Value + "<br>" + ex.ToString() + "<br>";
     }

     if ( shouldQueryUser )
     {
      this.SavedFileName = fileName;
      System.Text.StringBuilder javaScript = new System.Text.StringBuilder();
      
      javaScript.Append("\n<script type=text/javascript>\n");
      javaScript.Append("<!--\n");

      javaScript.Append("var overwriteVerification = window.confirm('Do you wish to overwrite?');\n");
      javaScript.Append("__doPostBack('FileOverwritePostBack', overwriteVerification);\n");

      javaScript.Append("// -->\n");
      javaScript.Append("</script>\n");
      
      RegisterStartupScript(scriptKey, javaScript.ToString());
     }
    }

    protected void deleteFile()
    {
     this.messageArea.Text = string.Empty;

     string fileName = this.SavedFileName;
     string tempFilePath = this.Server.MapPath("Temp") + "\\" + fileName;
     this.SavedFileName = string.Empty;

     try
     {
      if ( System.IO.File.Exists(tempFilePath) )   
       System.IO.File.Delete(tempFilePath);
     }
     catch(Exception ex)
     {
      this.messageArea.Text = "Error deleting file: " + fileName + "<br>" + ex.ToString() + "<br>";
     }
    }

    protected void moveFile()
    {
     this.messageArea.Text = string.Empty;

     string fileName = this.SavedFileName;
     string filePath = this.Server.MapPath("Uploads") + "\\" + fileName;
     string tempFilePath = this.Server.MapPath("Temp") + "\\" + fileName;
     this.SavedFileName = string.Empty;

     try
     {
      if ( System.IO.File.Exists(filePath) )   
       System.IO.File.Delete(filePath);

      // Move the file.
      System.IO.File.Move(tempFilePath, filePath);
     }
     catch(Exception ex)
     {
      this.messageArea.Text = "Error moving file: " + fileName + "<br>" + ex.ToString() + "<br>";
     }
    }

    private void Page_Load(object sender, System.EventArgs e)
    {
     // Insure that the __doPostBack() JavaScript is added to the page...
     this.GetPostBackEventReference(this, string.Empty);

     if ( this.IsPostBack )
     {
      string eventTarget = (this.Request["__EVENTTARGET"] == null) ? string.Empty : this.Request["__EVENTTARGET"];
      string eventArgument = (this.Request["__EVENTARGUMENT"] == null) ? string.Empty : this.Request["__EVENTARGUMENT"];

      if ( eventTarget = "FileOverwritePostBack" )
      {
       if ( eventArgument == "true" )
        this.moveFile();
       else
        this.deleteFile();
      }
     }
    }

    Note that RegisterOnSubmitStatement, RegisterStartupScript, RegisterClientScriptBlock, etc have changed since version 1.1 and you will get a compiler warning with the above.
    See http://msdn2.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.aspx for more info.

    NC...

Page 1 of 1 (2 items)