Title:       Custom File Upload - .NET Software Development - Javascript and Scripting.FileSystemObject
Author:      Greg Dubinovskiy 
Email:       [email protected]
Environment: Javascript, .NET
Keywords:    Browse for Folder - Browse for File - Upload File Control - using Javascript - using Scripting.FileSystemObject
Level:       Intermediate
Description: Browse for Folder - Browse for File - Upload File Control - using Javascript - using Scripting.FileSystemObject -
		How to access the directory path string (which will be used to download the files) - How to set any available default values for the directory bvrowser -
		Ability to allow a user to browse for a file on the desktop to be written/uploaded to the directory on the server - 
		Programmatically invoke the file browse dialog with JavaScript - Load file into javascript variable - Browse for file html button done with javascript - 
		Reading file contents using javascript - Browse local file with Web Browser - Replacing input type=file with JavaScript - 
		JavaScript based File Manager - Uploading image files with a Javascript - How to browse a Folder in a Web application developed using JavaScript.
		

Section      Miscellaneous
SubSection   General

Siccolo Development Articles - Javascript Application Development - .NET Software Development - Browse for Folder - Browse for File - Upload File Control - using Javascript

Select a drive:  









1. Using Scripting.FileSystemObject to display Drives, Folders and Files:

In client-side browser script, you can use Scripting.FileSystemObject to "explore" drives, folders and files presented on the client machine.


For example, to get list of drives and display them in a list box:
function show_drives_list()
{
	try
	{
		//list <select> element:
		var list = document.getElementById("selectDriveList");
		//clear list:
		list.options.length=0
		list.options[list.options.length]=new Option("<select drive>", "", false, false);

		var fso = new ActiveXObject("Scripting.FileSystemObject");

		var enumDrives = new Enumerator(fso.Drives);

		for (; !enumDrives.atEnd(); enumDrives.moveNext())
		{
			var driveItem = enumDrives.item();
			var driveLetter = driveItem.DriveLetter;
			//alert (driveItem.DriveLetter);
			list.options[list.options.length]=new Option(driveLetter + ":", driveLetter+ ":", false, false);
		}
	}
	catch (_err)
	{
		alert ("Failed to Populate Drive List:\n" + _err.description );	
	}
}
Once Drives list is populated, then Folders can be shown for a selected drive:
function show_folders( parent_folder_path )
{
	try
	{
		//list  <select> element:
		var list = document.getElementById("selectFolderList");
		//clear list:
		list.options.length=0
		list.options[list.options.length]=new Option("<select folder>", "", false, false);

		var fso = new ActiveXObject("Scripting.FileSystemObject");

		var parentFolder = fso.GetFolder(parent_folder_path);

		var enumFolders = new Enumerator(parentFolder.SubFolders);

		for (; !enumFolders.atEnd(); enumFolders.moveNext())
		{
			var folderItem = enumFolders.item();
			list.options[list.options.length]=new Option(folderItem, folderItem, false, false);
		}
		return true;

	}
	catch (_err)
	{
		alert ("Failed to Populate Folder List:\n" + _err.description );	
		return false;
	}
}
Once Folder is selected, then Files are in corresponding list:
function show_files( parent_folder_path )
{
	try
	{
		//list <select> element:
		var list = document.getElementById("selectFileList");
		//clear list:
		list.options.length=0

		var fso = new ActiveXObject("Scripting.FileSystemObject");

		var parentFolder = fso.GetFolder(parent_folder_path);

		var enumFiles = new Enumerator(parentFolder.files);

		for (; !enumFiles.atEnd(); enumFiles.moveNext())
		{
			var fileItem = enumFiles.item();
			list.options[list.options.length]=new Option(fileItem.name, fileItem, false, false);
		}

		return true;
	}
	catch (_err)
	{
		alert ("Failed to Populate File List:\n" + _err.description );	
		return false;
	}
}
And once File is selected - put it in text box on the page:
function select_file ( file_path)
{
	document.getElementById("textSelectedFile").value = file_path;
}


2. Build Web Service to allow file uploading (ASP.NET/C#):

On you server-side, we will need a web service that would accept file content as byte array and file name:


using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;


[WebService(Namespace = "http://www.siccolo.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
	...
	...
	[WebMethod(Description = "Test File Upload")]
    	public bool DoTestUpload(   string FileName,
                                byte[] FileIn,
                                out string ErrorInfo)
    	{

        	bool ToDebug = UploadSettings.ToDebug();
        	FileUpload fu = new FileUpload();

	        try
        	{
            		if (ToDebug)
            		{
                		fu.SaveToLog("Request from [" +
                                    this.Context.Request.UserHostAddress +
                                    "]"                                    );
            		}

	            	string FilePath = UploadSettings.FilePath();
        	    	if (FilePath == "")
            		{
                		throw (new System.Exception("Settings.File Path is not set"));
	            	}
	
        	    	if (ToDebug) { fu.SaveToLog("FilePath [" + FilePath + "]"); }


		       if (!fu.SaveUploadToFile(FileName, FileIn, out ErrorInfo))
        	    	{
                		return false;
	            	}

	            	ErrorInfo = "";
        	    	return true;
	        }

	        catch (Exception ex)
        	{
	            ErrorInfo = ex.Message;
	            if (ToDebug) { fu.SaveToLog(ex.ToString()); }
        	    return true;
	        }
	}
	...
	...
}
Where SaveUploadToFile() method in FileUpload class:
...
...
public bool SaveUploadToFile(string FileName,
                               byte[] FileIn,
                               out string ErrorInfo)
    {
        try
        {
            string FullFileName = UploadSettings.FilePath();
            FullFileName = Path.Combine(FullFileName, FileName);

            System.IO.FileStream fs = File.OpenWrite(FullFileName);

            this.SaveToLog("SaveUploadToFile().FileIn.Length=" + FileIn.Length.ToString());

            fs.Write(FileIn, 0, FileIn.Length);
            fs.Close();
            
            ErrorInfo = "";
            return true;
        }
        catch (Exception ex_save_file)
        {
            ErrorInfo = ex_save_file.Message;
            this.SaveToLog(ex_save_file.ToString());
            return false;
        }
    }
...
...


3. Call Web Service from Javascript

And to call our just created Web Service from JavaScript: 1) add an element <div id="serviceUploadFile" style="BEHAVIOR:url(webservice.htc)" onresult="on_upload_done();">
2) call web service:

var service_url = "http://www.microsoft.com/service.asmx?WSDL"; 
var serviceDiv = document.getElementById("serviceUploadFile");

function do_file_upload ( file_name, file_bytes)
{
	try
	{
		var errorInfo;
		alert ("Sending:" + file_name + " Size:" + file_bytes.length);
		var result = serviceDiv.Service.callService("DoTestUpload",file_name,file_bytes, errorInfo); 

		alert ("result:" + result + " error:" + errorInfo);
	 	
		return true;
	}
	catch (_err)
	{
		alert ("Failed to upload a File List:\n" + _err.description );	
		return false;
	}
}

And that's it. Click to see JavaScript source code for this article




Article keywords: .NET, C#, Javascript, File upload, Scripting.FileSystemObject, Drive, Folder, File, Drives, Folders, Files, GetFolder, Subfolders, getElementById, options, new Option(), new Enumerator(),

Back To Articles Page

Free Mobile Management For SQL Server(s!) - Siccolo - SQL Management ToolQuestions? Suggestions? Concerns? - email me to [email protected]    Greg Dubinovsky © 2008
or share your thoughts at Siccolo Blog

Web being sponsor - Mid-Atlantic Processing. Well being sponsor - Clarity MediSpa. Hairless sponsor - Clarity MediSpa Laser Hair Removal.
Siccolo - SQL Server Management Tool For Mobile Devices is packed with built-in functionality and tools. Siccolo delivers a rich set of management tools for both DBAs and sys admins. SQL Server management has always been an area of DBA concern. The new Management Tool For Mobile Devices - Siccolo - has simple "Enterprise Manager" and the "Query Analyzer". Siccolo is a management tool for the MS SQL Server with administration capabilities and a database query tool. The administration features provide users the ability to browse database structures. An integrated query tool allows users to quickly create, edit and execute SQL queries and scripts. Siccolo also provides an export tool to allow users to easily save and email execution results. Siccolo helps database professionals save time and increase their productivity by utilizing a more efficient approach to database management - use their Windows Mobile empowered device while sipping margarita on the beach For increased security, Siccolo is configured to run under SSL with IIS authentication.