Upload Files with C#
I get asked rather often how to write code to upload files from a webpage to the webserver. The following code will upload a file and save it on the webserver using ASP.Net 1.1 and C#.
There code can be reduced by taking out the functionality to check the file types, but I like to make sure that the file type is an expected type. The code below allows you to upload .gifs, .jpeg, .jpg, .swf, but not other types which is a safety precaution worth the extra lines of code.
This code saves the uploaded image to the "Images" folder of the web application which is set in the first couple of lines. You may need to alter that, an it determines the website folder at run time so it doesn't need to be changed to run in different websites.
On the HTML view of the page, you need to place a Text box with a browse button which can be done with the following html tag:
<INPUT id="filUpload" type="file" name="filUpload" runat="server">
Now put a button on the screen and call it "cmdUpload", then double click the button to go to the click event and add this code in your code behind file:
private void cmdUpload_Click(object sender, System.EventArgs e)
{
string myFolder = "Images"
if(base.Settings.fldAdsFolder.Length > 0)
{
string uploadPath = base.MappedApplicationPath + myFolder + @"\";
this.litUploadError.Text = "Your file has been posted to the server.";
//before actual upload so upload func can overwrite if error.
UploadImage(uploadPath);
}
else
{
this.litUploadError.Text = "You must set the Ads Folder in Settings first.";
}
}
private bool UploadImage(string UploadPath)
{
bool retVal = true;
string strFileName;
string strFilePath;
string strType;
string strFolder = UploadPath; //save it here
string err = "";
string ext = "";
if(filUpload.Value != "")
{
strFileName = base.GetFileName(filUpload.PostedFile.FileName);
strType = filUpload.PostedFile.ContentType;
bool allowedType = false;
switch(strType)
{
case("image/gif"):
allowedType = true;
ext = ".gif";
break;
case("image/jpg"):
allowedType = true;
ext = ".jpeg";
break;
case("image/jpeg"):
allowedType = true;
ext = ".jpeg";
break;
case("image/pjpeg"):
allowedType = true;
ext = ".jpeg";
break;
case("application/x-shockwave-flash"):
allowedType = true;
ext = ".swf";
break;
default:
allowedType = false;
err = "The file is not an allowed file type (ie: gif, jpg, jpeg, swf)";
break;
}
if (allowedType)
{
// Create the directory if it does not exist.
if(!Directory.Exists(strFolder))
{
string strFolderToCreate = strFolder;
if(strFolder.EndsWith(@"\"))
strFolderToCreate = strFolder.Substring(0,(strFolderToCreate.Length-1));
Directory.CreateDirectory(strFolderToCreate);
}
// Save the uploaded file to the server.
strFilePath = strFolder + strFileName;
if(File.Exists(strFilePath))
{
//only shows file name to user
err = strFileName + " already exists on the server!";
}
else
{
filUpload.PostedFile.SaveAs(strFilePath);
}
}
else //not allowed type, only images allowed
{
err = strFileName + " is not a valid image file.";
}
}
if(err.Trim().Length > 0)
{
this.litUploadError.Text = err.Trim();
retVal = false;
}
return retVal; //if it returns as "false" don't continue to save.
}
//You should really stick this function in a different class where you can reuse it better.
public static string MappedApplicationPath
{
get
{
string APP_PATH = System.Web.HttpContext.Current.Request.ApplicationPath.ToLower();
if(APP_PATH == "/") //a site
APP_PATH = "/";
else if(!APP_PATH.EndsWith(@"/")) //a virtual
APP_PATH += @"/";
string it = System.Web.HttpContext.Current.Server.MapPath(APP_PATH);
if(!it.EndsWith(@"\"))
it += @"\";
return it;
}
}