Tag Archives: photo

Creating a custom “Upload Photo” page for your website

Here are the codes you can use to create a page where your website users are able to upload their own photos or files to a specific folder on the server.

Note: To use this code, you will need a Windows Server.

First copy and paste this entire code into your favorite text editor:

<%@ Page Language="c#" AutoEventWireup="true" EnableViewState="false" %>
<%@import namespace="System.IO" %>
<%@import namespace="System.Web.UI.HtmlControls" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Sample Upload Photos Page</title>
<meta name="description" content="Sample Photo Upload Code" />
<meta name="copyright" content="TheLibzter.com copyright 2010" />
<meta name="author" content="TheLibzter.com, http://thelibzter.com/" />
<meta name="classification" content="business" />
<meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" />
<meta http-equiv="content-language" content="en-us" />
<meta http-equiv="content-style-type" content="text/css" />
<meta http-equiv="content-script-type" content="text/javascript" />
<meta http-equiv="imagetoolbar" content="no" />
<meta name="distribution" content="global" />
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />

<style>

.page {
margin-left: 50px;
margin-top: 50px;
}

</style>

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

// FIRST, SET THESE SERVER VARIABLES AS YOU LIKE...

// Set your Upload Folder Path. If left blank, it will upload the file to the webroot, or root or main folder of your website. You can enter a subfolder instead, if you have one setup under your webroot. Example: "/MyPhotos/". If you have set up a WebApplication subfolders on your server, it will use that as the webroot, and then apply your folder path to it.

string UploadFolderPath = "/UserPhotos/";//default upload location is webroot

// Add an empty image or sample image to the image control in the webpage. This image will be replaced by your uploaded image in the browser. Note: The path to this file is the same as the upload image path you set above.

string EmptyImageName = "pic.jpg";

// Now go to the bottom of this page to set the "file extensions" or type of file you want to upload (you set the file types in the RegularExpressionValidator below). You can set it for Photos, like .JPG and .PNG or others. Just remember, most browsers only support JPG, GIF, PNG and BMP file types.

// Leave these as is...
string SystemFilePath = "";

public void Page_Load(object ob, System.EventArgs ev)
{

// First make sure all paths are setup correctly.
if (Request.ApplicationPath == "/")
{
if (UploadFolderPath == "")
{

SystemFilePath = "/";
}
else
{
SystemFilePath = UploadFolderPath;
}
}
else
{
SystemFilePath = Request.ApplicationPath + UploadFolderPath;
}

this.UploadedPhotoDisplay.Src = SystemFilePath + EmptyImageName;

}

void UploadFile(object ob, EventArgs ev)
{

// Make sure all form fields have valid information.
if (Page.IsValid)
{

string UploadedFileNameOnServer = System.IO.Path.GetFileName(UploadFileInput.PostedFile.FileName);

string PhysicalServerFileLocation = Server.MapPath(SystemFilePath);

string FinalFilePath = PhysicalServerFileLocation + UploadedFileNameOnServer;

if(UploadFileInput.PostedFile != null && UploadedFileNameOnServer != "")
{
try
{
//Post file and Success Message.

UploadFileInput.PostedFile.SaveAs(FinalFilePath);

OutputMessage.InnerHtml = "<strong>File uploaded successfully! Thank You!</strong> (Your File Name: " + UploadedFileNameOnServer + ")<hr />";

// If file is an image, update hidden spacer image with image for preview.

if (UploadFileInput.PostedFile.ContentType.IndexOf("image") >= 0) //check if its image file
{
//Assign image properties dynamically on successful upload.

this.UploadedPhotoDisplay.Src = SystemFilePath + UploadedFileNameOnServer;
this.UploadedPhotoDisplay.Border = 1;
this.UploadedPhotoDisplay.Align = "left";
this.UploadedPhotoDisplay.Alt = "My Uploaded Photo";
}

}
catch (Exception e)
{
// If server exception is thrown by .NET, show that below. You can comment this out if you dont want to show this. Of you can add in your own text message for your users.
OutputMessage.InnerHtml = "Error: There was a Server Error saving your photo named '" + UploadedFileNameOnServer + "'<br />Server Error: " + e.ToString() + "<hr />";
}

}
else
{
// If the file failed for any reason, or empty image or code was uploaded, this message will be shown. You can change this as you like.
OutputMessage.InnerHtml = "Your photo was not uploaded: Please choose a different file to upload, or try again.<hr />";
}
}
}
</script>

</head>

<body>
<div>
<form enctype="multipart/form-data" runat="server" id="Form1">

<span id="OutputMessage" runat="server" />

<%-- Customize what file formats you accept in the code validator below. So, be sure to use the extension validator below. --%>
<asp:regularexpressionvalidator runat="server" errormessage="<strong>Your Photo was Not Uploaded</strong>: Only valid image types are allowed. Please upload a file in one of those formats.<hr />" validationexpression="^((([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))*|(.*))(\.jpg|\.JPG|\.jpeg|\.JPEG|\.bmp|\.BMP)$" controltovalidate="UploadFileInput" enabled="true" visible="true"  enableclientscript="false"  display="dynamic" id="Regularexpressionvalidator1" style="color:#990022;"></asp:regularexpressionvalidator>

Select a Photo to Upload by Pressing the Browse Button Below:
<br />
<input id="UploadFileInput" type=file runat="server" name="UploadFileInput" />
<br />
<input type=button id="UploadFileButton" value="Upload Photo" onserverclick="UploadFile" runat="server" name="UploadFile" />
<hr />
(Your photo will appear below in its actual size)
<br />
<br />
<img id="UploadedPhotoDisplay" border="0" runat="server" />

</form>
</div>
</body>
</html>

Save the file as “filename.aspx”. You can name it whatever you want, as long as it has the .aspx extension.

Next, we will set the “variables” in the code so that the paths are correct. The first path to edit is the location where you want the new photos to be uploaded to. You can use an existing folder, create a specific folder for the new photos, or, if you don’t specify a folder, the images will automatically be uploaded to the webroot.

string UploadFolderPath = "/UserPhotos/";//default upload location is webroot

You can upload an empty image or sample image that will be displayed when users first come to the page and will be replaced by the newly uploaded image in the browser. Upload the sample image to the folder where all of the user-uploaded images will go. Note: The path to this file is the same as the upload image path you set above, so you don’t need to specify which folder on your server it is in as long as it is in the folder where all the uploaded images will go.

string EmptyImageName = "pic.jpg";

Now go to the bottom of the page and set the “file extensions” or type of file (JPG, PNG, PSD) you will allow to be uploaded. Just remember, most browsers only support JPG, GIF, PNG and BMP file types. Edit this code to specify which files you will allow:

<%-- Customize what file formats you accept in the code validator below. So, be sure to use the extension validator below. --%>

<asp:regularexpressionvalidator runat="server" errormessage="<strong>Your Photo was Not Uploaded</strong>: Only valid image types are allowed. Please upload a file in one of those formats.<hr />" validationexpression="^((([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))*|(.*))(\.jpg|\.JPG|\.jpeg|\.JPEG|\.bmp|\.BMP)$" controltovalidate="UploadFileInput" enabled="true" visible="true"