Chapter 3: Uploading Images

Contents

3.1 Browser-Based File Uploading

In many real-life applications such as online photo albums, before an image is resized it has to be uploaded to the Web server by the user. Under classic ASP, one needs a third-party server-side upload component to capture uploaded images, such as Persits Software's AspUpload.

Under .NET, no third-party component is necessary as file uploading can be performed using the built-in <asp:FileUpload> control. The following code sample uploads a file and places it in the c:\upload folder:

<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.IO" %>

<script runat="server" language="c#">

void OnUpload(object sender, EventArgs e)
{
  if(FileUpload.HasFile)
  {
    try
    {
      string filename = Path.GetFileName(FileUpload.FileName);
      FileUpload.SaveAs( @"c:\upload\" + filename );
      lblStatus.Text = "Success!" ;
    }
    catch(Exception ex)
    {
      lblStatus.Text = "The upload failed: " + ex.Message;
    }
  }
}
</script>

<form id="form1" runat="server">
<asp:FileUpload id="FileUpload" runat="server" />
<asp:Button runat="server" id="btn" text="Upload" onclick="OnUpload" />
<br />
<asp:Label runat="server" id="lblStatus"/>
</form>>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.IO" %>

<script runat="server" language="vb">

Sub OnUpload(ByVal sender As Object, ByVal e As EventArgs)
  If FileUpload.HasFile Then
    Try
      Dim filename As String =
      Path.GetFileName(FileUpload.FileName)
      FileUpload.SaveAs("c:\upload\" + filename)
      lblStatus.Text = "Success!"
    Catch ex As Exception
      lblStatus.Text = "The upload failed: " + ex.Message
    End Try
  End If
End Sub

</script>

<form id="form1" runat="server">
<asp:FileUpload id="FileUpload" runat="server" />
<asp:Button runat="server" id="btn" text="Upload" onclick="OnUpload" />
<br />
<asp:Label runat="server" id="lblStatus"/>
</form>

In addition to HTML forms, files can also be uploaded to the server using various 3rd-party client-side JavaScript apps, ActiveX controls and Java applets which provide additional features not found in the forms, such as the ability to upload an entire directory, dragging-and-dropping, or a progress bar. These products are outside the scope of this discussion, as we are focusing on the server-side scripting only.

3.2 Resizing Uploaded Images

The following code sample enables you to upload an image, resize it to the specified width, and then save the thumbnail to disk in the same folder as the script file.

<%@ Page Language="C#" debug="true" %>

<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="Persits.Jpeg"%>

<head runat="server">

<script runat="server" language="c#">
void OnUpload(object sender, EventArgs e)
{
  if( FileUpload.HasFile)
  {
    try
    {
      string filename = Path.GetFileName(FileUpload.FileName);
      string filepath = Server.MapPath(".") + "\\" + filename;
      FileUpload.SaveAs(filepath);

      // Resize image
      JpegManager objJpeg = new JpegManager();
      JpegImage objImage = objJpeg.OpenImage(filepath);

      int Width;
      if( !int.TryParse(txtWidth.Text, out Width) )
      {
        lblStatus.Text = "Invalid width value";
        return;
      }

      objImage.PreserveAspectRatio = true;
      objImage.Width = Width;

      string thumbnail = objImage.SaveUnique(filepath+"_small.jpg");

      imgOutput.ImageUrl = thumbnail;

      lblStatus.Text = "Success!";

    }
    catch(Exception ex)
    {
      lblStatus.Text = "Failure: " + ex.Message;
    }
  }
}
</script>
</head>

<body>
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload" runat="server" /><br />
Desired Width: <asp:TextBox ID="txtWidth" runat="server" value="200"/><br/>
<asp:Button runat="server" ID="btn" Text="Upload" OnClick="OnUpload"/><br/>
<asp:Label runat="server" ID="lblStatus" />
<br /><br />
<asp:Image runat="server" ID="imgOutput" />
</form>
</body>
</html>
<%@ Page Language="vb" debug="true" %>

<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="Persits.Jpeg"%>

<head runat="server">

<script runat="server" language="vb">
Sub OnUpload( sender As Object, e As EventArgs)
  If FileUpload.HasFile Then
    Try
      Dim filename As String = Path.GetFileName(FileUpload.FileName)
      Dim filepath As String = Server.MapPath(".") + "\" + filename
      FileUpload.SaveAs(filepath)

      ' Resize image
      Dim objJpeg As JpegManager = New JpegManager()
      Dim objImage As JpegImage = objJpeg.OpenImage(filepath)

      Dim Width As Integer
      If Not Integer.TryParse(txtWidth.Text, Width) Then
        lblStatus.Text = "Invalid width value"
        Exit Sub
      End If

      objImage.PreserveAspectRatio = True
      objImage.Width = Width

      Dim thumbnail As String =
      objImage.SaveUnique(filepath + "_small.jpg")

      imgOutput.ImageUrl = thumbnail

      lblStatus.Text = "Success!"
      Catch ex As Exception
      lblStatus.Text = "Failure: " + ex.Message
    End Try
  End If
End Sub
</script>
</head>

<body>
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload" runat="server" /><br />
Desired Width: <asp:TextBox ID="txtWidth" runat="server" value="200"/><br/>
<asp:Button runat="server" ID="btn" Text="Upload" OnClick="OnUpload"/><br/>
<asp:Label runat="server" ID="lblStatus" />
<br /><br />
<asp:Image runat="server" ID="imgOutput" />
</form>
</body>
</html>

Click the links below to run this code sample:

3.3 Memory Uploads

The following code sample is similar to the previous one, except that we use the memory upload feature of the FileUpload control. The uploaded file's bytes are retrieved via the FileBytes property and passed to AspJpeg.NET's OpenImage method.

void OnUpload(object sender, EventArgs e)
{
  if( FileUpload.HasFile)
  {
    try
    {
      // Resize image from memory
      JpegManager objJpeg = new JpegManager();
      JpegImage objImage = objJpeg.OpenImage(FileUpload.FileBytes);

      int Width;
      if( !int.TryParse(txtWidth.Text, out Width) )
      {
        lblStatus.Text = "Invalid width value";
        return;
      }

      objImage.PreserveAspectRatio = true;
      objImage.Width = Width;

      string filepath = Server.MapPath(".") +
      "\\" + Path.GetFileName(FileUpload.FileName);
      string thumbnail = objImage.SaveUnique( filepath );

      imgOutput.ImageUrl = thumbnail;

      lblStatus.Text = "Success!";
    }
    catch(Exception ex)
    {
      lblStatus.Text = "Failure: " + ex.Message;
    }
  }
}
...
Sub OnUpload( sender As Object, e As EventArgs)
  If FileUpload.HasFile Then

  Try
    ' Resize image from memory
    Dim objJpeg As JpegManager = New JpegManager()
    Dim objImage As JpegImage = objJpeg.OpenImage(FileUpload.FileBytes)

    Dim Width As Integer
    If Not Integer.TryParse(txtWidth.Text, Width) Then
      lblStatus.Text = "Invalid width value"
      Exit Sub
    End If

    objImage.PreserveAspectRatio = True
    objImage.Width = Width

    Dim filepath As String = Server.MapPath(".") +
    "\" + Path.GetFileName(FileUpload.FileName)
    Dim thumbnail As String = objImage.SaveUnique(filepath)

    imgOutput.ImageUrl = thumbnail

    lblStatus.Text = "Success!"
    Catch ex As Exception
      lblStatus.Text = "Failure: " + ex.Message
    End Try
  End If
End Sub
...

Click the links below to run this code sample: