This script does one of two things. First it lets the user browse the file structure of any directory on the web server (permissions permitting of course) and lets them request any file by clicking on it. Only the directory you specified as root and its sub directories can be explored. The script won't let a user go above the directory you have specified as the root directory.The main advantage of this is that you can keep your files outside of your inetpub directory away from the control of the webserver. This means that your users can only access the files via your scripts. The actual location of the files on the disk is hidden from the user, and if they wish to request a file they can only get it via your script. This allows you to build in any access features you might want to add such as ensuring people have logged in to your website before they get any files. Or maybe you want certain users to download only certain files, or you might only want to give access to requests with certain domains in the HTTP_REFERER variable. By taking control of the file structure away from IIS and into your ASP script you gain full control over your files and who gets them. When a user clicks on a file to download it the script works out the correct MIME type so that the file behaves in exactly the same was as if they were getting it from IIS normally. ie jpg and gif files will show in the browser, zip files will prompt for a download, .doc files will embed themselves in the browser. And just like normal links users can right-click and select to save the file to their hard drive instead. Each directory is rendered as a basic HTML table. I'll leave it up to you how you decide to pretty up the interface. [bold]Browse.asp[/bold] <%@ Language=VBScript %><% option explicit dim sRoot, sDir, sParent, objFSO, objFolder, objFile, objSubFolder, sSize %> <META content="Microsoft Visual Studio 6.0" name=GENERATOR><!-- Author: Adrian Forbes --><% ' This is the root directory that the explorer will browse. Make sure there is no backslash () ' at the end. Also make sure that show.asp has an identical sRoot variable. sRoot = "c:webfiles"
' Get the directory relative to the root directory sDir = Request("Dir")
' Add a backslash sDir = sDir & "\"
Response.Write "<h1>" & sDir & "</h1>" & vbCRLF
' Create a copy of FileSystemObject Set objFSO = CreateObject("Scripting.FileSystemObject") on error resume next ' Get a handle on the folder Set objFolder = objFSO.GetFolder(sRoot & sDir) if err.number <> 0 then Response.Write "Could not open folder" Response.End end if on error goto 0
' We want a link to the parent folder also ' Get the full path of the parent folder sParent = objFSO.GetParentFolderName(objFolder.Path)
' Remove the contents of sRoot from the front. This gives us the parent ' path relative to the root folder ' eg. if parent folder is "c:webfilessubfolder1subfolder2" then we just want "subfolder1subfolder2" sParent = mid(sParent, len(sRoot) + 1)
Response.Write "<table border=""1"">"
' Give a link to the parent folder. This is just a link to this page only pssing in ' the new folder as a parameter Response.Write "<tr><td colspan=3><a href=""browse.asp?dir=" & Server.URLEncode(sParent) & """>Parent folder</a></td></tr>" & vbCRLF
' Now we want to loop through the subfolders in this folder For Each objSubFolder In objFolder.SubFolders ' And provide a link to them Response.Write "<tr><td colspan=3><a href=""browse.asp?dir=" & Server.URLEncode(sDir & objSubFolder.Name) & """>" & objSubFolder.Name & "</a></td></tr>" & vbCRLF Next
' Now we want to loop through the files in this folder For Each objFile In objFolder.Files if Clng(objFile.Size) < 1024 then sSize = objFile.Size & " bytes" else sSize = Clng(objFile.Size / 1024) & " KB" end if ' And provide a link to view them. This is a link to show.asp passing in the directory and the file ' as parameters Response.Write "<tr><td><a href=""show.asp?file=" & server.URLEncode(objFile.Name) & "&dir=" & server.URLEncode (sDir) & """>" & objFile.Name & "</a></td><td>" & sSize & "</td><td>" & objFile.Type & "</td></tr>" & vbCRLF Next
Response.Write "</table>" %>
[bold]show.asp[/bold] <%@ Language=VBScript %><% option explicit dim sFile, sRoot, sDir, sExt, objShell, objFSO, sMIME, objStream
' Author: Adrian Forbes -->
' Make sure this is the same sRoot variable that is defined in browse.asp sRoot = "c:webfiles"
' Get the directory relative to the root folder sDir = Request("dir")
' Get the file we're going to show sFile = Request("file")
' We need to know the MIME type for the file we are about to view. In ' order to get this we need to know the file's extension. ' We could use string functions to get the file extension but we've going ' to be lazy and use FileSystemObject set objFSO = server.CreateObject("Scripting.FileSystemObject") sExt = objFSO.GetExtensionName (sFile) set objFSO = nothing
' Now we have the extension, the file's MIME type is held in the registry at ' HKEY_CLASSES_ROOT.<ext>Content Type ' Create an instance of Wscript.Shell to let us read the registry Set objShell = Server.CreateObject("Wscript.Shell") On Error Resume Next ' Get the MIME type sMIME = objShell.RegRead("HKEY_CLASSES_ROOT." & sExt & "Content Type") On Error GoTo 0 if len(sMIME) = 0 then ' If there is no registered type then return octetstream. This will prompt ' the user with the "Open or Save to disk" dialogue. sMIME = "application/octetstream" end if set objShell = nothing
' Tell the browse the content type Response.ContentType = sMIME
' And the name of the file Response.AddHeader "Content-Disposition", "filename=" & sFile & ";"
' Now we need to pipe the file to the browser, to do this we ' will use the ADODB.Stream Set objStream = Server.CreateObject("ADODB.Stream") objStream.Open ' Set the type as Binary objStream.Type = 1 ' Load our file objStream.LoadFromFile sRoot & sDir & sFile
' And send it to the browser Response.BinaryWrite objStream.Read
objStream.Close Set objStream = Nothing %>
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
More ASP Code Articles More By Adrian Forbes developerWorks - FREE Tools! | The XO laptop (of the One-Laptop-Per-Child initiative) is an inexpensive laptop project intended to help educate children around the world. The XO laptop includes many innovations, such as a novel, inexpensive, and durable hardware design and the use of GNU/Linux as the underlying operating system. The XO also includes an application environment written in Python with a human interface called Sugar, accessible to everyone (including kids). Explore the Sugar APIs and learn how to develop and debug a graphical activity in Sugar using Python. FREE! Go There Now!
| | | | Download the Rational Application Developer (RAD) v7.5 open beta code and start developing applications for the JEE5 standard which features EJB3.0, JPA, JSF 1.2, JSP 2.1 and Servlet 2.5 standards. When you use this beta you will see how you can increase developer productivity for already existing applications with improved support for refactoring, as well as adding new features to existing applications. In addition, the beta provides tooling for JD Edwards, Oracle, SAP, Siebel and PeopleSoft to improve the developer productivity with these enterprise systems. FREE! Go There Now!
| | | | You might know that you can pull XML data into OpenOffice's spreadsheet program, Calc, but did you know that you can create a filter to make word-processing documents out of data stored as XML? This tutorial shows you how to use OpenOffice's import/export filters to open your XML data as though it's just a plain document. From there, users can edit the document much more naturally and then save it back to its native format. You can also use this feature to easily turn your documents into XML data. FREE! Go There Now!
| | | | JavaServer Faces (JSF) technology, a server-side framework that offers a component-based approach to Web user-interface development, has come a long way. JSF 1.2 (incorporated into Java Enterprise Edition 5) has fixed some JSF pain points and added some nice features. This tutorial series covers how to get started with JSF 1.2. It's heavy on examples and light on theory -- just what you need to get started quickly. FREE! Go There Now!
| | | | As systems increase in complexity, communication between systems and software teams becomes more and more difficult. Now, there’s a way to improve product quality and communication.<br />Read the “Model Driven Systems Development” white paper to see how. Also included in this kit are more educational white papers, customer examples, tutorials, informative Webcasts, and best practices for designing, building and managing systems.<br /> FREE! Go There Now!
| | | | IBM DB2 9.5 provides new options for tighter security, and allows for more granularity and flexibility in administration of the database. This tutorial is the second of two tutorials that cover roles and trusted contexts. Follow the exercises in this tutorial, and learn how to take advantage of the new DB2 feature trusted contexts in combination with other essential e-business technologies such as Web services, Web application server, and DB2 database server. FREE! Go There Now!
| | | | Ken Krugler, co-founder of code search company Krugle, and Laura Merling, vice president of Marketing and Business Development for Krugle, join to talk about the ins and outs of code search and what it means as a new feature for developerWorks users. FREE! Go There Now!
| | | | This tutorial presents an innovative use of the well-known Really Simple Syndication (RSS) format's associative properties to emulate the functionality of a simple relational database. It demonstrates using RSS channels to store contact information and meeting information -- much as a personal address book and calendar does. It uses RSS elements and attributes such as items and guids to create a neural-network-like mesh of related data. FREE! Go There Now!
| | | | Regression testing -- in which code is thoroughly tested to ensure that changes have not produced unexpected results -- is an important part of any development process. But many testing environments neglect the terminal-based applications that still form the backbone of many industries. In this tutorial, you'll learn how the Rational Functional Tester Extension for Terminal-Based Applications works with other Rational Functional Tester to help test terminal-based applications quickly and easily. FREE! Go There Now!
| | | | Get a free trial download of the latest version of IBM Rational Performance Tester V7.0.1, a load and performance testing solution for teams concerned about the scalability of their Web-based applications. Combining multiple ease-of-use features with granular detail, Rational Performance Tester simplifies the test-creation, load-generation and data-collection processes that help teams ensure the ability of their applications to accommodate required user loads. FREE! Go There Now!
| | | | All FREE IBM® developerWorks Tools! | |