Click here to Skip to main content
Click here to Skip to main content

ASP.NET File Uploader with Overwrite Message

By , 3 Dec 2008
Rate this:
Please Sign up or sign in to vote.

fileuploader1.GIF

fileuploader2.GIF

Introduction

This ASP.NET application is a file uploader dialog box that can be called from classic ASP. It is designed for use in an intranet site. The file uploader displays an overwrite warning as a popup or a warning message. The overwritten file is archived with a time stamp appended to the filename. Checking if the file already exists turned out to be the biggest obstacle. The FileExists Java function uses an ActiveX control that causes browser security warnings. The workaround was to access a code-behind routine by calling AJAX Web Services.

Background

I needed a file uploader dialog box for my ASP Classic intranet site but I couldn't find anything that met my needs. I wanted to prompt the user before overwriting an existing file. Also, I wanted the selected filename to be displayed after the upload was complete. It seems that the FileUploader control clears the filename after uploading a file. I also needed the old file to be archived for the user.

Using the code

Open the project only if you have already installed AJAX.

This project requires IE6, ASP.NET 2.0, AJAX, and JavaScript. The project is self contained with all the needed files and images to run as a demo. Directory permissions must be correctly set on the server to allow the Internet guest account to write to the directories.

Variables must be set in the sample HTML page and in the web.conf to match your needs. Be sure you set testupload.htm as the startup page for the project.

The code can be published into a subdirectory on the website by changing the root directory setting in the web.conf file. Don't forget to set the virtual directory to ASP.NET.

Parent HTML page JavaScript code

The parent page can be any HTML or ASP page in the website that calls the file uploader dialog. The IE routine uses the showModalDialog window opener to display the dialog. Non-IE browsers will use the regular window.open function. The file name is returned to the parent page to populate the textbox with either the full server path or a partial path according to the web.conf setting.

The calling arguments are set in the parent page to control the function of the overwrite prompt. The overwrite prompt can be set to a popup, non-popup message, or no prompt. The old file will be archived with a date/time stamp if the archive location is set.

//set variables here

var btestNonIE = false; //set to false - **** for testing only *****
var sReturnForm = "edit_Content";
var sReturnField = "FileName";
var sUploadFolder = "pending";

//use only one value: [popup, message, none]
//none value will archive without prompting if Archive dir is set
var sOverwritePrompt = "popup" 

// archives old file if value set (regardless of overwrite prompt)
//will also create sub dir if path is more than one level
var sArchiveFolder = "archive/december";

// end of variables to set

function Upload() {
  var rValue="";
  var sOptions = "status=no, resizable= no, scrollbars= no, " + 
                 "toolbar= no,location= no, menubar= no'";
  var sFormSize = "";

  if (navigator.appName == "Microsoft Internet Explorer" 
                && btestNonIE != true) { //btestNonIE is just for testing
    //IE Browser
    sOptions = "status:no; unadorned:yes; " + 
               "scroll:no; help:no; resizable:no; toolbar:no";
    var sRequests = "?folder=" + sUploadFolder;
    sRequests += "&archive=" + sArchiveFolder;
    sRequests += "&overwrite=" + sOverwritePrompt;
    rValue = showModalDialog('FileUploader.aspx' + sRequests + 
             '', 'FileUploader','dialogHeight:220px; dialogWidth:650px;' + 
             sOptions + '');
    if (rValue != undefined) {
      update_field(rValue,sReturnForm,sReturnField);
    }
  }else{
    //Not IE Browser
    var sRequests = "?folder=" + sUploadFolder;
    sRequests += "&archive=" + sArchiveFolder;
    sRequests += "&retForm=" + sReturnForm;
    sRequests += "&retField=" + sReturnField;
    sRequests += "&overwrite=" + sOverwritePrompt;
    window.open('FileUploader.aspx' + sRequests + 
                '','FileUploader', 'height=220, width=650," + 
                sOptions + "');
  }
}
function update_field(sNewValue,sForm,sField)
{
  eval("document." + sForm + "[sField].value = sNewValue;");
}

The ASP.NET code-behind for the Web Method FileExists routine

This code is called by the ASP.NET program's JavaScript listed below. We can now use the System.IO library to check if the file exists on the server. No browser security warning messages will display because the server side code is being called.

<WebMethod()> _
Shared Function CheckFileExists(ByVal FileName As String) As Boolean
  'use web methods to check if file exists
  'called from javascript code
  If (System.IO.File.Exists(FileName)) Then
    Return True
  Else
    Return False
  End If
End Function

ASP.NET default page code using JavaScript for the FileExists routine

This JavaScript code is in the default.aspx page. Using AJAX Web Methods, we can now call server side code from client side code. When the user clicks on the file upload button, the JavaScript calls the above code-behind and checks if the file exists. The user is prompted, or a warning message displays in the file uploader dialog.

This could be done by using JavaScript, but the browser security settings on the PC must allow JavaScript ActiveX without prompting the user. Web Methods allow client side code to run native VB.NET code on the server.

There are two Web Methods calls. One for the popup, and one for the warning message that displays in a label control. The page is submitted after the user clicks OK to overwrite and the file is uploaded.

Hidden variables are used to transfer data between the JavaScript and the code-behind routines.

function CheckFileExists(){
  //use PageMethods to call code behind routine
  var sOverwrite = document.frmUploadFile.hOverwrite.value;
  var sDestFolder=document.frmUploadFile.hDestFolderPath.value;
  var sUploadFile=document.getElementById('uploadFile').value;
  var sDestFilePathName=GetDestFileName(); 

  if (sOverwrite == "none" || sOverwrite == "" || 
                                  sOverwrite == "message") {
    //no overwrite message - just check if file exists and postback
    PageMethods.CheckFileExists(sDestFilePathName,FileExistsCallBackNoMessage);
    return false;
  }

  //prompt user with confirmation that file exists
  document.getElementById("hFileExists").value="false";
  if(sDestFilePathName.length == 0) {return false}
  if (sOverwrite == "popup") {
    //show confirm box and post back 
    PageMethods.CheckFileExists(sDestFilePathName,FileExistsCallBack);
  }
    return false;
}

function FileExistsCallBack(result){
  //if file exists on server, confirm with user
  if(result) {
    //file exists so prompt user
    if(confirm("File already exists. Do you want to overwrite?")) {
      document.getElementById("hFileExists").value="true";
      __doPostBack('btnSave','');
    }
  }
  else
    //file doesn't exists on server.. So upload it
    __doPostBack('btnSave',''); 
  }
function FileExistsCallBackNoMessage(result){
  //if file exists on server, no confirmation message
  if(result) {
    document.getElementById("hFileExists").value="true";
  }
  __doPostBack('btnSave',''); 
}


function FileExistsCallBackMessage(result){
  //callback from FileBrowseChangeMessage
  //if file exists on server, display overwrite button only
  if(result) {
    var objUploadLabelMessage=document.getElementById("lblUploadMessage");
    var objSaveButton=document.getElementById("btnSave");
    document.getElementById("hFileExists").value="true";
    EnableSaveButton();
    //change save button text to overwrite and messge to overwrite values 
    objSaveButton.src="Images/btnOverwrite.jpg";
    //hide cancel button and show overwrite button so code behind routine is used
    var objButtonCancel=document.getElementById("btnCancel");
    objButtonCancel.src="Images/blank.gif";
    var objButtonCancelOverwrite=document.getElementById("btnCancelOverwrite");
    objButtonCancelOverwrite.src="Images/btnCancel.jpg";
    objUploadLabelMessage.style.forecolor="orangered";
    objUploadLabelMessage.innerText="Caution! Destination File exists." + 
                                    " Click Overwrite to replace or Cancel."; 
    document.frmUploadFile.imgBeforeMessage.disabled=false;
    document.frmUploadFile.imgBeforeMessage.src="Images/icon_caution.gif";
  }
}


function GetDestFileName(){
  var sDestFolder = document.frmUploadFile.hDestFolderPath.value;
  var sUploadFile = document.getElementById('uploadFile').value;
  var sDestFilePathName = sDestFolder + "\\" + FileNameFromPath(sUploadFile);
  return sDestFilePathName;
}

Conclusion

Run the demo project and change the settings to see how the file uploader dialog functions. The project code contains many remarks to help with the logic. Not all code is shown above. This is the only way I could find to get around the browser security messages.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

BrianLaF
Web Developer
United States United States
Started programming in Business Basic in the 1980's and acquired my AS in Computer Science at that time. Promoted to IS Manager after one year of programming (sink or swim).
Self taught in SMC Basic, Visual Basic, C Shell, perl, ASP, JavaScript, vb.net, asp.net.
Now working as a Network Administrator at a hospital in Northern California.
Fell into a webmaster role when implementing the company's intranet website to support documentation.

Comments and Discussions

 
Generalgood job PinmemberArlen Navasartian18-Jan-10 21:04 
Questioncopied code? PinmemberOwen Gunter6-Sep-09 23:30 
AnswerRe: copied code? [modified] PinmemberBrianLaF7-Sep-09 5:07 
GeneralNice PinmemberBob Housedorf4-Dec-08 10:20 
This looks awesome! Next time I need to do this, I'll have a good sample to work from.
 
Thanks much!

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140415.2 | Last Updated 4 Dec 2008
Article Copyright 2008 by BrianLaF
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid