Христофоров Юрий
В этой статье я на примере расскажу, как используя ASP (Active Server Pages) можно построить содержимое каталога Web аналогично тому, как это выглядит на FTP сервере.
Постановка задачи: На Web-сервере есть каталог, например: C:InetPubwwwrootuser1. Пусть данный каталог имеет несколько вложенных каталогов и набор файлов в этих каталогах. Примерная структура папок представлена на Рис. 1.
Рис. 1.
В каждом из представленных на рисунке каталогах может находиться неограниченное количество файлов, либо некоторые из каталогов могут быть пустыми. Необходимо представить содержимое папки user1 на Web-странице в дружественном для пользователя виде.
Интересной особенностью скрипта является то, что применяя страницу с фреймами (кадрами), можно построить меню пользователя.
Результат должен выглядеть примерно следующим образом:
Находимся в папке C:Inetpubwwwrootuser1folder1subfolder2:
На данном скриншоте показан пример меню. Страница menu.htm разделена на два фрейма. В левом фрейме находится файл list_files.asp, а правый фрейм используется для отображения файлов, ссылки на которые находятся в левом фрейме. В левом фрейме можно свободно перемещаться по папкам. Т.о. можно организовать меню пользователя.
Решение: Ключ к решению данной задачи - это использование MicrosoftR Scripting Library. Нас будет интересовать такой объект этой библиотеки, как FileSystemObject. FileSystemObject предоставляет объектную модель доступа к файловой системе. Далее, пользуясь средствами языка написания сценариев VBScript, выполняемого на Web-сервере, можно написать одну ASP-страницу, которая будет выполнять всю работу. Итак, приступим.
Листинг файла list_files.asp:
<%Response.Expires=0%> 'Отключаем кэширование страницы <HTML> <BODY> <!-Серверный сценарий <% Dim root_folder, root_vfolder, curr_dir, curr_dir2, temp_arr 'root_folder - переменная для хранения физического пути к корневой папке USER1 root_folder = "c:inetpubwwwrootuser1" 'root_vfolder - переменная для хранения виртуального пути к папке USER1 'localhost - имя Вашего сервера root_vfolder = "localhost/user1" 'curr_dir2 - имя текущей (активной) папки curr_dir2 = Request.QueryString("dir") 'Имя получаем из URL 'curr_dir - полный физический путь к текущей папке. Получается конкатенацией строк, 'содержащихся в переменных root_folder и curr_dir2. curr_dir = root_folder & curr_dir2 'temp_arr - временный массив 'Получаем массив, содержащий названия каталогов текущей папки. temp_arr = ShowDirList(curr_dir) 'Сортируем массив строк temp_arr = SortStr(temp_arr) %> <table border=0> <% 'Вызов процедуры, осуществляющей вывод названий подкаталогов текущего каталога. Call Main_Print(temp_arr,1) 'Получаем массив, содержащий имена файлов текущей папки. temp_arr = ShowFilesList(curr_dir) 'Сортируем массив строк temp_arr = SortStr(temp_arr) 'Вызов процедуры, осуществляющей вывод имен файлов текущего каталога. Call Main_Print(temp_arr,0) %> </table> <% 'Очистка содержимого массива Erase temp_arr |
Далее следует текст функций и процедур, используемых в сценарии.
Функции: ShowFilesList - возвращает массив, содержащий имена файлов текущей папки.
ShowDirList - возвращает массив, содержащий названия каталогов текущей папки.
SortStr - сортирует массив строк.
Процедура: Main_Print - осуществляет вывод в HTML-формате содержимое текущего каталога.
Продолжение листинга файла list_files.asp:
Function ShowFilesList(folder) Dim fs, f, f1, fc, i 'Определяем динамический массив для хранения имен файлов ReDim farr(0) 'Создаем объект FileSystemObject Set fs = CreateObject("Scripting.FileSystemObject") Set f = fs.GetFolder(folder) Set fc = f.Files i=0 'В цикле заполняем массив именами файлов текущей папки For Each f1 In fc farr(i) = LCase(CStr(f1.Name)) 'Преобразуем имя к нижнему регистру символов i = i + 1 'Увеличение размера массива ReDim Preserve farr(i) Next 'Возвращаем результат ShowFilesList = farr End Function |
Function ShowDirList(folder) Dim fs, f, f1, fc, i 'Определяем динамический массив для хранения названий каталогов ReDim dirarr(0) Set fs = CreateObject("Scripting.FileSystemObject") Set f = fs.GetFolder(folder) Set fc = f.SubFolders i=0 'В цикле заполняем массив именами каталогов текущей папки For Each f1 In fc dirarr(i) = LCase(CStr(f1.Name)) i = i + 1 ReDim Preserve dirarr(i) Next 'Возвращаем результат ShowDirList = dirarr End Function |
Function SortStr(arr) Dim t,i,j 'Сортировка методом "пузырька" 'UBound - возвращает верхний индекс массива For j = 0 To UBound(arr)-1 For i = j + 1 To UBound(arr)-1 'StrComp - сравнивает две строки 'Возвращает "-1", если строка1 < строка2; "0", если строка1=строка2; "1", если строка1 > ' строка2. If StrComp(CStr(arr(i)), CStr(arr(j)), vbTextCompare) < 0 Then t = arr(j) arr(j) = arr(i) arr(i) = t End If Next Next 'Возвращаем результат SortStr = arr End Function |
Sub Main_Print(arr,flag) 'flag = 1 - вывод для каталогов 'flag = 0 - вывод для файлов Dim i,k,tmp i = 0 Select Case flag Case 1 'Если находимся в подкаталоге, то надо предусмотреть возможность вернуться 'на уровень выше If curr_dir2 <> "" Then 'Ищем последнее вхождение символа разделителя каталогов "" k = InStrRev(curr_dir2,"") If k <> 0 Then 'Получаем имя каталога верхнего уровня tmp = Mid(curr_dir2,1,k-1) Response.Write "<tr>" 'Вывод HTML 'Для украшения используем графический файл open.gif - изображение открытой папки. Response.Write "<td><img src='open.gif'></td>" 'Формируем ссылку на верхний каталог Response.Write "<td><a href='list_files.asp?dir=" & tmp & "'>" & " .. " & "</a></td></tr>" End If End If 'Основной цикл вывода названий каталогов For i = 0 To UBound(arr)-1 Response.Write "<tr>" Response.Write "<td><img src='close.gif'></td>" Response.Write "<td><a href=' list_files.asp?dir=" & curr_dir2 & "" & arr(i) & "'>" & arr(i) & _ "</a></td></tr>" Next 'Вывод имен файлов Case 0 'Основной цикл вывода имен файлов For i = 0 To UBound(arr)-1 Response.Write "<tr>" Response.Write "<td><img src='doc.gif'></td>" 'Заменяем "" на "/" для использования в URL 'Атрибут target нужен для указания ссылки на фрейм Response.Write "<td><a href='" & root_vfolder & Replace(curr_dir2,"","/") & "/" & arr(i) & _ "' target='main'>" & arr(i) & "</a></td></tr>" Next End Select End Sub %> </BODY> </HTML> |
Далее необходимо написать страницу menu.htm, содержащую два фрейма, как было показано выше. Листинг приведен ниже:
<HTML> <HEAD> </HEAD> <FRAMESET COLS="150,*"> <FRAME NAME="contents" SRC="list_files.asp"> <FRAME NAME="main" SRC="empty.htm"> </FRAMESET> </HTML> |
Файл empty.htm представляет собой пустой файл-заглушку для корректного отображения страницы в браузере Netscape Navigator.
<!-empty.htm <HTML> </HTML> |
Файлы list_files.asp, menu.htm, empty.htm необходимо поместить в каталог на Web-сервере с правом Script.
Далее в браузере набираем, например, localhost/scripts/menu.htm
Пример работы скрипта приведен на Рис.2.
Рис.2.
Исходный файл проекта прилагается: files.zip
Другие работы по теме:
Работа с файлами (лабораторная работа)
Лабораторная работа №2 Т е м а: Р а б о т а с ф а й л а м и. Задание: 1)Создание каталога 1-го уровня; провести проверку. 2)Создание каталога 2-го уровня в каталоге 1-го уровня; установка этого каталога.
Работа с каталогами (лабораторная работа)
Лабораторная работа №1 Т е м а : Р а б о т а с к а т а л о г а м и Задание: 1)Просмотр корневых каталогов и подкаталогов дисков командами DIR,DIR/W,DIR/P. В отчете представить 3-4 характерные строки отображения содержимого каталогов при выполнении команд DIR(DIR/p) и DIR/W, т.е. показать форму отображения имен файлов и каталогов.
Работа с файлами лабораторная работа
Лабораторная работа №2 Т е м а: Р а б о т а с ф а й л а м и. Задание: 1)Создание каталога 1-го уровня; провести проверку. 2)Создание каталога 2-го уровня в каталоге 1-го уровня; установка этого каталога.
The Future Of The Internet Essay Research
Paper The Future Of The Internet In Today’s world of computers, the internet has become part of ones regular vocabulary. The internet is everywhere, in the news, the newspaper,
Cable Modems Are The Wave Of The
Future Essay, Research Paper There are several different methods to achieve communication between computers. In the case of the Internet, most people use a telephone modem to establish a connection between their computer and the computer that gives them access to the Internet. Normally, the computer that gives them access to the Internet, referred to as an ISP (Internet Service Provider) can only have a limited number of users on it at any given time.
Dsl Vs Cable Essay Research Paper 22
Dsl Vs. Cable Essay, Research Paper 2.2 Why focus on Internet access? Internet access has several desirable properties as an application to consider for exercising residential infrastructure. Internet technology is
Internet Structure Essay Research Paper The Internet
Internet Structure Essay, Research Paper The Internet connects nearly 400 million users worldwide and is an essential part of how we work, play, communicate, and conduct commerce. We use the Internet in ways that seemed unimaginable The term “Internet” refers to the global information system that — (i) is logically linked together by a globally unique address space based on the Internet Protocol (IP) or its subsequent extensions/follow-ons. (ii) is able to support communications using the Transmission Control Protocol/Internet Protocol (TCP/IP) suite or its subsequent extensions/follow-ons, and/or other IP-compatible protocols; and (iii) provides, uses or makes accessible layered on the communications and related infrastructure described herein.”, either publicly or privately, high level services.
Internet Censorship Essay Research Paper Censorship of
Internet Censorship Essay, Research Paper Censorship of inappropriate material has been an issue with every form of mass media. Now the new and upcoming Internet is becoming the focus. Software makers and service providers are choosing what the public should see. Does this seem right? How can a stranger choose what another person or their family sees on the Internet? Parents and adults should choose what they and their children are exposed to on the Internet.
Addicted To Internet Essay Research Paper ADDICTED
Addicted To Internet Essay, Research Paper ADDICTED TO INTERNET In the past several years many people have been getting computer literate. As time passes by, people also have been getting addicted to their
Cyber Porn And Internet Privac Essay Research
Paper Cyber Porn and Internet Privacy Two computer ethic controversies There are many controversial questions about computer issues today but there are many debates with cyber porn and internet privacy. The Internet is accessed by millions of people everyday, especially children. Cyber porn is all over the Internet and can be accessed by anyone from anywhere whether in school, home, or on the job.
Internet Shopping Essay Research Paper Internet shopping
Internet Shopping Essay, Research Paper Internet shopping is one of today’s most popular activities for shopper people. Shopping on the Internet can make people relax and take their time to think about the product that they want to buy. Internet shopping is getting used to be more familiar to people in this society today’s.
The Internet Essay Research Paper Information has
The Internet Essay, Research Paper Information has long been sought out by many generations throughout time. It is a powerful tool that has often been hard to find, until the evolution of the Internet. The Internet has
Internet Good Or Bad Essay Research Paper
The question that many people have on their minds is, “Is the Internet good or bad?” In this article, we will give you information so that you can make an educated decision for yourself. We will first concentrate on the bad issues of the Internet. Then, we will tell you the advantages of having the Internet. We hope this will help you make a good decision for your family or business.
Internet Piracy Essay Research Paper In this
Internet Piracy Essay, Research Paper In this day and age where technology is rampant and advance, it is critical that we comprehend the possibilities that such technology has, no matter whether it is good or bad. From our very own households, we can now ?get connected? and experience this technology first hand.
The Internet Vs The Library Essay Research
Paper The Internet vs. the Library Overall, when one compares the Internet vs. the Library, the Library is superior. This is because, though it takes a bit longer to use, the Library has a standard information research tool; the Dewey decimal system. This organized system makes finding books simple, and with the added assistance of a librarian, finding information can be easy.
Education On The Internet Essay Research Paper
Education on the Internet In today’s society, the internet has become a very important learning tool. It is used for day to day activities, such as a place to look up research, a method of getting in touch with friends and family, and somewhere to go to find information about almost anything imaginable. The most popular uses of the internet include entertainment and education.
Is The Internet Really Free Essay Research
Paper First Amendment rights for Net users: The Internet can be credited for being the greatest invention of the twentieth century. Along with this marvelous invention comes great controversy, should the Internet be
America Online Essay Research Paper America Online
America Online Essay, Research Paper America Online To Unveil Flat Fee For Internet Access The Internet is becoming more popular and more widely used, and the Market for internet access is growing rapidly. To stay
Child Pornography On The Internet Essay Research
Paper Child Pornography On The Internet The Internet has caused an increase in the production and distribution of child pornography. Child pornography arrests have increased 220%, with most cases involving the use of computers (Trebilcock 1). Most child pornography on the Internet has been taken from magazines produced in the seventies and early eighties, which encourages new images to be created.
Internet Legislation Essay Research Paper subject
Internet Legislation Essay, Research Paper subject = LAW title = Internet Legislation papers = Internet Legislation With the recent popularity of the Internet many topics concerning it have hit main
The Internet Market In Kuwait Essay Research
Paper Many competitive markets have been appeared in Middle East lately, and specially in Kuwait. The One which I will discuss is the Internet competitive market in Kuwait . Internet has been a great demand in all over the world. In 1992, The ministry of communication in Kuwait provided the internet service.
Computers Essay Research Paper Why We StartedInternet
Computers! Essay, Research Paper Why We Started Internet Mental Health is a free encyclopedia of mental health information. It was designed by a Canadian psychiatrist, Dr. Phillip Long, and programmed by his colleague, Brian Chow.
Internet Advertising Essay Research Paper Internet AdvertisingInternet
Internet Advertising Essay, Research Paper Internet Advertising Internet Advertising is the way of the future and it is very evident since many companies and businesses have their own web sites and advertisements are located all over the World Wide Web. The Internet or World Wide Web is quickly becoming the most effective way for a business to advertise their products or services to customers.
The Internet In Public Schools Essay Research
Paper “The Internet: A Necessity Or Luxury In The Public School Classroom.” Modems, e-mail, www’s and ’s – are these phrases merely a part of a worldwide fad, or are they here to stay? And if they are, then what role should they play in the future of public education? Many times, new things come along, and we all jump on the big boat of opportunity so quickly that we forget to look at the long term merits of what we’re boarding.
The Internet And World Wide Web Defined
Essay, Research Paper Christopher L. Isaacs 1010 ? Technical Writing Extended Definition 00 March 6th The ?Internet? and ?World Wide Web? Defined In recent years the Internet and World Wide Web (WWW) have become more and more popular as an information resource. Many people believe that the WWW is the same as the Internet.
Internet PC
’s: Next Wave Or Nonsense? Essay, Research Paper Internet PC’s: Next Wave or Nonsense? Call them what you will: Internet appliances. Network terminals. The whole
Making A Web Page Essay Research Paper
Making a Web Page For my science project I chose to create a web (internet) page, dealing with science. This project consists of using a computer and a html editor to create a page that can be found on the internet. The next paragraph will explain how to make an internet page. The steps to making a web page to post on the internet, is very easy.
The Internet 2 Essay Research Paper The
The Internet 2 Essay, Research Paper The Internet The Internet is a place with an infinite of possibilities. It is the biggest technological breakthrough ever created. The Internet symbolizes freedom. It is uncensored and unregulated by the government. And that is hard to come by these days. With the Internet anything is possible.
Internet Marketing Essay Research Paper Internet Marketing
Internet Marketing Essay, Research Paper Internet Marketing and Associated Topics Computers and the Internet are becoming faster and capable of new and exciting things every day. Through this evolution, businesses have begun to reach out to consumers in new, unprecedented ways. With the amazing growth of users of the Internet, and the enormous growth that is expected to continue, businesses are aware that there is tremendous potential to provide and promote products and services in previously inconceivable ways.
The Old Man And The See Essay
, Research Paper THE HISTORY OF INTERNET In the beginning of the 1970`s in USA was an older military network called ARPANET converted to Internetvork wish was a network between networks. Accept a few Universities