Pure ASP File Upload

by Jacob Gilley


As a regular to ASP 101, I feel it neccesary to give a little back to the site that keeps me on top of things in the world of ASP. And so, I give you the FileUploader ASP Library. In a nutshell, the FilerUploader library is simply a single ASP include that provides an object-oriented approach to getting files from Internet clients.

I have seen numerous "pure ASP" upload solutions, some you even had to purchase, that did the job, but required you to wade through pages of code just to see how things worked. Then there are the COM components that you can buy that do what you want and more, but cost an arm and leg to obtain. What I wanted was something simple, centralized, easy to use and FREE! The FileUploader Library was the solution and now I want to share my work with fellow developers.

NOTE - YOU MUST HAVE VBSCRIPT v5.0 INSTALLED ON YOUR WEB SERVER FOR THIS LIBRARY TO FUNCTION CORRECTLY. YOU CAN OBTAIN IT FREE FROM MICROSOFT WHEN YOU INSTALL INTERNET EXPLORER 5.0 OR LATER.

The library consists of two VBScript classes: FileUploader and UploadedFile. The FileUploader is the top-level object in the model and is the only one that you will need to instantiate.

Here is how to do it: (this assumes that you have included "upload.asp")

<%
  Dim MyUploader
  Set MyUploader = New FileUploader

%>

Now once your FileUploader object is initialized, you can begin recieving the uploaded data from the client by a single call to the Upload() method.

<%
  MyUploader.Upload()
%>

Or, since Upload() is the default method, you can use a shortcut and start the upload process like this: (Use one or the other, not both)

<%
  MyUploader()
%>

Once that is complete, you can begin access and saving the file to your hard-drive or to a database. The uploaded files are accessed through the Files Collection of the FileUploader object. The Files Collection is a set of UploadedFile objects that represent each file uploaded.

Here is an example of how to enumerate the Files Collection and write each uploaded files' information to the browser:

<%
  Dim File
  For Each File In MyUploader.Files.Items
    Response.Write "File Name:" & File.FileName
    Response.Write "File Size:" & File.FileSize
    Response.Write "File Type:" & File.ContentType
  Next

%>

Here is an example of how to access a specific file in the Files Collection using the HTML file input element name as the Index:

<%
  Response.Write "File Name:" & MyUploader.Files("file1").FileName
  Response.Write "File Size:" & MyUploader.Files("file1").FileSize
  Response.Write "File Type:" & MyUploader.Files("file1").ContentType

%>

For simplicity sake, I will be the using the For Each...Next variation for the following samples. Now, all the files are uploaded and its time to put them somewhere. There are two places you can save the uploaded files...on your hard-drive or to a database.

Here is how to save the files to disk:

<%
  Dim File
  For Each File In MyUploader.Files.Items
    File.SaveToDisk "C:\UploadedFiles"

  Next
%>

And how to save to a database: (Replace "MyUploadTable", "CONNECT STRING.." and field names accordingly)

<%

  Dim RS
  Dim File

  Set RS = Server.CreateObject("ADODB.Recordset")
  RS.Open "MyUploadTable", "CONNECT STRING OR ADO.Connection", 2, 2

  For Each File In MyUploader.Files.Items
    RS.AddNew

    RS("filename") = File.FileName
    RS("filesize") = File.FileSize
    RS("contenttype") = File.ContentType

    File.SaveToDatabase RS("filedata")

    RS.Update
  Next

  RS.Close  
%>

I think that should just about cover everything. I hope this helps out and that you found my blathering somewhat interesting. If you have any questions or comments about this article or the code provided, feel free to email me. (avis7@airmail.net)

You can download the library and sample files below (4 KB).

p34c3 +0 4|| c0d3rz!


Update: Pure ASP File Upload Gets a Speed Boost

Jacob Gilley's Pure ASP File Upload is an effective, free method for uploading user files to your server. Although well implemented, I found that the file I/O needed improvement. Concatenation is quite slow in VBScript and it was actually faster to write a single byte at a time to the disk than to concatenate the file prior to saving.

Here Robbert Nix's improved concatenation algorithm comes to the rescue. I stumbled upon this algorithm when searching for performance enhancements in VBScript. Essentially Nix's code allows Gilley's Pure ASP File Upload to return to concatenation as a viable method for preparing the file prior to saving.

Two files are included with this implementation: upload.asp and buffering.inc. These files are meant to be incorporated with the existing distribution for Gilley's Pure ASP File Upload. The upload.asp file replaces the existing version and the include file buffering.inc is used to improve upload time.

Note: if you replace your existing version of upload.asp you must also copy buffering.inc to the same directory! No changes in existing upload pages are required to take advantage of this upgrade.

Gilley's Pure ASP File Upload files are needed and can be found above.

You can download the updated upload.asp and new buffering.inc in a zip file, fileuploader_buffering.zip, below (3.4 KB)

--Will
Do Many Things ... Well
wbic16@hotmail.com


Update: Even Faster Yet...

It seems that the update above caught the atention of one of our other authors... here's his message:

Hello. I already have a few articles posted on your website so far. I just got your newsletter concerning ASP uploads: Update: Pure ASP File Upload Gets a Speed Boost

While this may be faster - it is still very slow. I have found a way around this in the past and had posted my findings on planet source code at:

http://www.pscode.com/vb/scripts/ShowCode.asp?txtCodeId=7361&lngWId=4

I am including the upload_files_without_com_v2.zip file (below) (28 KB) for you to go over and review with this message. The zip file also includes a screen shot to demonstrate the simplicity of the code, and also contains a working sample. It is commented well and uses classes for a more object-oriented approach. Rather then converting each character between ansi and unicode 1 at a time - this class calls the ADODB Stream object to do it all at once. ADO 2.5+ is required along with vbScript 5.0+

I have had very good reviews posted by others about this code on planet source code.

Allowing files to be translated quicker allows users to post larger files before the server times out. Happy Coding!

Lewis@Moten.com
http://www.lewismoten.com


Update: Listing the Files That Have Been Uploaded

Our "Pure ASP File Upload" article has been getting update after update recently and here's one more. When we left it last, updated files were getting entered into a database. This update brings a simple little script to display a list of those files. Here's the message:

I just wanted to share some code I came up with to display all the files uploaded to the database using Lewis Moten's code (which was very useful and fairly easy to use). I needed to create an area on our company website where the advertising and sales staff could share files back and forth easily but I found that Lewis's code only took care of the upload part. We needed to be able to view all the files as well.

Well, here it is. It just runs through the database until it reaches End Of File (EOF) and displays the filenames as links to that file. It requires Lewis Moten's DataFile.asp file to work but there is no need to modify it. The modifications have been made in my code to make it work with that file as is.


<%
Dim oConn
Dim oRS
Dim sSQL
Dim lngFileID

Set oConn = Server.CreateObject("ADODB.Connection")
oConn.Open("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" _
	& Server.MapPath("db\Files.mdb"))

sSQL = "SELECT FileID, FileName, Date FROM Files " _
	& "ORDER BY Date desc, FileName"

Set oRS = oConn.Execute(sSQL)

If oRS.EOF Then
	Response.Write("<font face=arial size=2><b>There are " _
		& "currently no files in the database.</b></font><br>")
Else
	Do While NOT oRS.EOF
		lngFileID = oRS("FileID").Value
		Response.Write("<a href=DataFile.asp?FileID=" _
			& lngFileID & " target=_blank>" _
			& oRS("FileName").Value & "</a><br>")
		oRS.MoveNext
	Loop
End If

oConn.Close
Set oRS = Nothing
Set oConn = Nothing
%>

The only thing that might throw people is that I've changed the path to the database since mine is stored in the "db" directory on my server therefore the path is db/Files.mdb. I've also included an ORDER BY clause in my sql statement to display the files from newest to oldest and then in alpha order by filename. This code can be placed anywhere on your page that you want the files displayed. You can also set it up to display the files in multiple columns across the page in a <table> instead of one long column down the page but you need to add additional "If NOT oRS.EOF Then" code before each new table cell. I've used this code on a page with other asp code so if you use it by itself you'd need to add the Option Explicit statement at the top.

Thanks for the great asp resource. Many of my peers have recommended your site to me when I've had questions about developing asp solutions for various things on my websites. Have a great day.

Regards,
Bryan Hovey

Thanks Bryan... I'm sure you're not the only one who needs this functionality. A number of our users are sure to find this helpful.



About the Author

From ASP101

Articles originally posted on ASP101.com

Downloads

Comments

  • VP

    Posted by James on 02/09/2014 08:17am

    I have similar problem to view the upload the file with the fileuploader class. Before I upgraded host server from Windows 2003 to 2008, iis5 to iis7, I have no problem to source this script for uploading files and images. However, after migrating to Windows 2008 and iis7, I still can upload to designate directory with same file size but can't view the file or image at all. Do you have any insight for the fix? Thanks lots

    Reply
  • Bug in clsField.cls

    Posted by Nick on 07/30/2013 11:18am

    Not all browsers pass the full file path in the content-disposition header, some pass the name only (Chrome for one). In that case the FileName property will be empty, as it depends on a "\" character to extract the file name from the path. Starting at line 198 in clsField.asp, change this: ' Parse File Name If Not InStrRev(pstrPath, "\") = 0 Then FileName = Mid(pstrPath, InStrRev(pstrPath, "\") + 1) End If To this: ' Parse File Name If Not InStrRev(pstrPath, "\") = 0 Then FileName = Mid(pstrPath, InStrRev(pstrPath, "\") + 1) Else 'NGB 30/7/2013: Not all browsers pass a full path, some pass filename only (Chrome) FileName = pstrPath End If To fix the bug.

    • I use Chrome almost exclusively

      Posted by Leonard on 09/18/2014 11:49pm

      Thanks. This fix worked for me.

      Reply
    Reply
  • De haute qualité, redresseurs ghd pas cher est le favori des jeunes

    Posted by lszouc553 on 07/16/2013 11:06am

    Le ressort de la boutique, il est beaucoup Cheap GHD Norge.Our lisseur ghd pas seulement pas cher mais la qualité est Veldig soutien-gorge, est la meilleure product.These ghd pas cher du monde a Flot différent versjoner av ghd stylers cheveux y hjelpe skjønnhet bevisst en y Öppna son Utseende de rêve . Ils sont conçus pour y do coiffure oppleve un grand, avec des résultats étonnants merkbart. Nous consacrons-nous ici å servir chaque client avec lisseur ghd produit beste et Best service.and ces ghd droit Rod Price mer tiltrekke you.We pense que vous nageoire vos lisseur ghd pas cher de favoris. [url=http://ghdpascherfer.webgarden.es/]lisseur ghd pas cher[/url] Si grande est la demande de rose ghd que dans l'approche de la saison des fêtes, les vendeurs sur eBay sont en mesure de facturer jusqu'à 200 £ pour un ghd rose. C'est un énorme £ 65 par rapport au prix de vente conseillé pour le rose ghd! En tant que tel, puisque l'aide ghd pink lever des fonds, ce qui pourrait être un facteur décisif dans les choix d'achat des gens. Mais peut-être une raison plus importante est qu'un grand nombre de femmes aiment des choses roses. Par conséquent, il n'est pas surprenant que, lorsque sortit ghd ghd pink, ce serait quelque chose qui tuerait à posséder! [url=http://ghdpascherferfr.webgarden.com/]ghd pas cher[/url] Troisièmement, ils ont également arrondis barils qui peuvent faire un fer GHD plus polyvalent que beaucoup d'autres types d'appareils de coiffure sur le marché. Si vous souhaitez modifier votre chevelure est souvent avantageux d'utiliser défrisants ghd peut aussi créer des vagues, sauts et loops.Endelig, vous devez sélectionner un fer GHD est conçu pour une utilisation dans une explosion ou frange. GHD IV styler Mini est parfait pour beaucoup moins de cheveux. Combinez ces excellentes caractéristiques redresseurs les plus complets, mais il est plus facile à utiliser sur des petits morceaux de hair.Maybe vous savez ce ghd lisseur

    Reply
  • Cheap Oakley Big Taco online store

    Posted by wmznldzpc on 06/24/2013 11:54am

    fake ray ban ,Oakley sunglasses is a good brand sunglasses while using highest quality of materials, the choice of Oakley, sunglasses, Oakley sunglasses, each many styles and colors. Today, Oakley in the world already has a lot more than 600 patents and 800 registered trademarks, product of glasses is dizzying. Oakleys Clearance ,Oakley, Sunglasses would you expect from your world leader in performance and innovative technology, unmatched processing towards the smallest detail, there is absolutely no trouble, just change a new lens group. Oakleys will undoubtedly be considered one of their unique class, has become the boom of an trend, they've already found many of the popular Hollywood performers. Cheap Oakley Rada ,Continuous development, in order that a good posture, the comparison in another article. The sun shine, including ultraviolet illumination, and other alike on the sun. The right pair of designer sunglasses in these two different, the thing is, reports of feeling if you live inside hot sun day of outdoor great distance. It is worth noting: if your frame or lens contaminated dust, sweat, grease, cosmetics and other warm water cleaning with a neutral detergent. A range of Websites Providers with the simplicity of the customer's request, select one of several people likely to end up accurate and appropriate glasses and identity. In fact, all through the Oakley sunglasses provide 100% UVA and UVB protection. Even non-colored fashion Oakley sunglasses provide same Ultraviolet protection. In addition to the design of top speed and excellence of the development of high-protection framework. Oakley will be worth your time and money of said and done, the people's lifestyle, sports or polarized sunglasses can buy the suitable product manufacturers from this. In year retro massive construction projects, Oakley glasses essential clothing accessories, and sometimes keep to the fashion trends go, sometimes they lead the popularity. Oakley sunglasses at least change the color of why people love the object itself, more real, natural landscape, but additionally to avoid glare. Oakley sunglasses they HDO (high-definition optical) is well know, and they continue to use this breakthrough technology inside their design. Oakley sunglasses sales with lots of styles so that you can choose. We provide Iridium lens coating to balance light transmission to offer the most effective visual type of the targeted environment.

    Reply
  • GHD IV Styler – min Perfekt verktøy

    Posted by pletchermtx on 06/14/2013 02:25pm

    [url=http://www.rettetangnorgenews.net/]ghd rettetang[/url] GHD rettetang sørger for at stylingen ikke blir for varm for farget hår. Det er faktisk ganske enkelt: Forskjellige hårtyper trenger forskjellige temperaturer for å reagere på styling. Varmen går lettere gjennom tynt hår enn tykt hår. Derfor har Satin Hair 7 Colour rettetang en intuitiv varmejustering som lar deg forhåndsinnstille temperaturen nøyaktig etter hårtypen (tynt, normalt, tykt hår). Og selv om du bruker effektknappen for å temme uregjerlige hårlokker, så vil du ikke utsette håret ditt for temperaturer på over 200 °C. Få flotte stylingresultater uten fare for for høye temperaturer og nyt den flotte hårfargen din lenger. [url=http://www.rettetangnewsnorge.com/ghd-omsorg]ghd rettetang pris[/url] Varmen går lettere gjennom tynt hår enn tykt hår. Derfor har Satin Hair 7 Colour rettetang en intuitiv varmejustering som lar deg forhåndsinnstille temperaturen nøyaktig etter hårtypen (tynt, normalt, tykt hår). Og selv om du bruker effektknappen for å temme uregjerlige hårlokker, så vil du ikke utsette håret ditt for temperaturer på over 200 °C. Få flotte stylingresultater uten fare for for høye temperaturer og nyt den flotte hårfargen din lenger.Tvert imot: de hindrer fuktighetstap fra stylingen ved å påføre unike satengioner til håret ditt! Disse negativt ladde ionene fester seg til det positivt ladde håret ditt og reduserer tørt, krusete hår og tiltrekker fuktighetspartikler fra lufta og sender dem dit hvor håret trenger det mest. [url=http://www.rettetangnorgenews.net/]rettetang ghd[/url] Rettetangen har roterende ledningfeste og tre ulike temperaturinnstillinger for ulike funksjoner og hårtyper, der makstemperaturen er 230 °C.Med den globale spenningsomformeren for 120-240V er rettetangen også perfekt å ha med på reisen, og du oppbevarer den sikkert i den medfølgende varmebestandige vesken i luksuriøs design.Elegant rettetang Paris som du både kan glatte og krølle håret med.

    Reply
  • Ghd fladjern med service, smukke flagrende hÃ¥r tilhører dig

    Posted by cheneason on 05/30/2013 12:22pm

    [url=http://www.beats-by-dr-dre5.webnode.es/]Beats by dr dre[/url] Nu skal vi starte det nye år. Du kan finde modeverdenen. Frisk stil model, har en god GHD håret dyrebar gave ting, så du skal være en god emne at diskutere med andre for at sikre, at alle kan diskutere, jeg ønsker at tale om dig. [url=http://www.beats-by-dr-dre5.webnode.es/]Beats by dr dre[/url] GHD annonceringsomkostninger i Storbritannien hvert år, mere end 100 millioner pund, enorme reklame gebyrer er meget velkendt i Storbritannien op den globale GHD brand. GHD produkter er primært salgsargument er dens emballage, emballage smukt, moderne design, relativt hurtig udskiftning, glat hår er enkel, bare tænde for kontakten, kan du bruge! [url=http://www.beatsbydrebaratos.blinkweb.com/]Beats by dre baratos[/url] Nu skal vi starte det nye år. Du kan finde modeverdenen. Frisk stil model, har en god GHD håret dyrebar gave ting, så du skal være en god emne at diskutere med andre for at sikre, at alle kan diskutere, jeg ønsker at tale om dig.

    Reply
  • Incredible approach for the shoes that you will understand more about today.

    Posted by BobHotgloff on 05/23/2013 02:42am

    Actual Solutions To Learn about shoes And Also The Way One Might Enroll with The shoes Top dogs [url=http://www.shoesja.biz/]アシックス[/url] Products and fabrication throughout Michigan : shoes will leave with no hasta la vista [url=http://www.shoesja.biz/adidas-アディダス-c-64.html]アディダス シューズ[/url] The most important sneakers Firm Dialogue - The Ones Who likes little or nothing triumphs?! [url=http://www.shoesja.biz/new-balance-ニューバランス-c-21.html]ニューバランス 574[/url] Recent questions on shoes addressed in addition to reasons why you should definitely look into each term of this specific study. [url=http://www.shoesja.biz/nike-ナイキ-c-44.html]ナイキ スニーカー[/url] Tips about how to fully understand every part there is to learn relating to shoes in 3 basic steps. [url=http://www.kutuja.com/]アディダス[/url] Ways to master anything there is to find regarding shoes in six very easy steps. [url=http://www.kutuja.com/adidas【アディダス】-c-1.html]アディダス シューズ[/url] All new queries about shoes replied to and as a consequence the reason why you have got to check out every single message of this specific document. [url=http://www.kutuja.com/new-balance【ニューバランス】-c-206.html]newbalance[/url] Further from the ultimate approach for the shoes you may find out more about as we speak. [url=http://www.kutuja.com/nike【ナイキ】-c-215.html]ナイキ[/url] The next double turn on shoes [url=http://www.shoesjp.biz/]アシックス[/url] Keys For shoes [url=http://www.shoesjp.biz/adidas【アディダス】-c-640.html]adidas アディダス[/url] An absolute double change on sneakers

    Reply
  • In invalid you bring into the world a suspicions here less the rules, fundamental satisfied tie on the nosebag a look at the FAQ, as it potency already be experiencing been answered start with

    Posted by carpitpni on 04/16/2013 02:02am

    Our Resultant Clothing experts from made collages showing you what your [url=http://www.hollistercorfrance.fr]hollister[/url] favorite celebrities are wearing and what we be struck aside to catapult up with a view yard sale you that is greatly similar. We are current to write this “Famousness [url=http://www.abercrombiesfrancevparise.fr]abercrombie[/url] Sighting” a weekly practice so that you can scold like your favorite celebrity! This week we are featuring the up to the minute, Rhianna with an laid bankrupt denim look. Dream unwavering to copy our [url=http://www.airjordanfrpaschere.fr]air jordan[/url] blog to observe these spectacular, contented watch hypnotic Polyvore blog posts! If I possibly to bear a shopper secure in who is a sympathetic argue in the direction of something that's not identifiable in the mass, I'd figure out pass it on. I refrain whole's hands on on the characteristic of master b crush parent. There's nothing I can't let abolished of except in the directorship of my books. I watch over my books because [url=http://www.abercrombieufrancersoldes.fr]abercrombie[/url] I intent them in return the purposes of reference. I boyfriend reading up on the brands that I buy off from so it [url=http://www.airjordanspasuchere.fr]air jordan[/url] was great that the marque had lots of info. Unfortunately you can’t categorically do what it says on the stamp here but some of the tip points sign by [url=http://www.hollisterfrancevmagesin.fr]hollister[/url] Skunkfunk are that they rusticate before sailboat, usefulness inborn cotton, wood crumble cellulose (Modal and Lyocell) and recycled polyester. Conducive to their packaging they drink bioplastic [url=http://www.abercrombievandfitchuks.co.uk]abercrombie uk[/url] (made from Cornstarch) and advantage as much recycled wrapping periodical as possible. Their clothes are also often multi occasion and reversible [url=http://www.monclerfrancermagasinsfr.fr]doudoune moncler[/url]. But in November, we each had a chance to decide a liveliness fit in with and look [url=http://www.airjordanzchaussuren.com]air jordan[/url] at things from a unusual perspective. We had been in so intensely, plugging away, racing on to the next gismo that we hadn’t charmed the hour to look up [url=http://www.michaelukorsua.com]michael kors[/url] and entreat ourselves what we surely wanted.We’ve dedicated two and a half years to creating a brand and a commodity that exceeded our (wildest) expectations. We’ve lettered more than we constantly soup噊n [url=http://www.hollisterucoboutiquer.fr]hollister france[/url] possible. We’ve met implausible people and made expensive connections. We’ve discovered a passion championing something we didn’t be informed of with we had.But with all of this nurturing, we’ve recently realized that rdevelopment threads [url=http://patrimoine.agglo-troyes.fr/BAM/louboutinpascher.html]louboutin pas cher[/url] is no longer something we be taken captive knee-high to a grasshopper of, or be conscious of we difficulty, to put into practice what we were meant to do.

    Reply
  • save file to database

    Posted by Nilofer on 03/26/2013 11:14pm

    i am able to upload the file and save it to disk..it works fine..when i use save it to database i am getting thank you message..but in db it does not saved..it is empty..can you help me

    Reply
  • Get date from Request.Form fields

    Posted by kyle sullens on 03/25/2013 10:51pm

    I have a form where a user can upload a document and give it a title/description. There are fields on the form where the user can type this information. In the code-behind, when I reference the Request.Forms collection, I lose the ability to do a BinaryRead (such as the Upload() method does). If do the UPload() first, I am not able to read from the Request.Form collection. Any way to pass data between from the user facing ASP page to the ASP code page that saves the file to disk and writes tot he DB? Thanks!

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Today's agile organizations pose operations teams with a tremendous challenge: to deploy new releases to production immediately after development and testing is completed. To ensure that applications are deployed successfully, an automatic and transparent process is required. We refer to this process as Zero Touch Deployment™. This white paper reviews two approaches to Zero Touch Deployment--a script-based solution and a release automation platform. The article discusses how each can solve the key …

  • Learn How A Global Entertainment Company Saw a 448% ROI Every business today uses software to manage systems, deliver products, and empower employees to do their jobs. But software inevitably breaks, and when it does, businesses lose money -- in the form of dissatisfied customers, missed SLAs or lost productivity. PagerDuty, an operations performance platform, solves this problem by helping operations engineers and developers more effectively manage and resolve incidents across a company's global operations. …

Most Popular Programming Stories

More for Developers

RSS Feeds