473,725 Members | 2,173 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to upload whole files with ASP

jhardman
3,406 Recognized Expert Specialist
Have you ever wanted to upload files through a form and thought, "I'd really like to use ASP, it surely has that capability, but the tutorial I used to learn ASP didn't mention how to do this."? Have you looked around trying to find simple solutions but didn't want to wade through pages of complex code? Have you balked at paying for premade solutions that are probably overkill for your particular project?

I'd like to walk you through the basic steps right here. Yes, it is fairly easy, and yes you can do it all with only ASP. Is it straight forward? Not exactly, but if you know the basics of manipulating long strings and using the scripting.fileS ystemObject then you can do it.

Note
Much of this code has been adapted from an article from visualBuilder.c om which uploads and displays files. I have made the code more linear and added the subroutine which saves the file.

Step 1: Set up
First there are two things you need to get ready before you actually work on the upload. You need a form and you need a folder. By "folder" I mean you need a folder for which the anonymous web user has permission to save files. I suggest this be a sub-folder off of your main web directory and that you not give IIS permission to execute scripts from this folder (to help prevent malicious code uploads). In my example I am using a folder called "temp" right off of my root web directory.

By "form" you may think I am being overly obvious, but there are actually a couple changes you may need to make to your basic form in order to accept file uploads. The first is a change in your form tag:
Expand|Select|Wrap|Line Numbers
  1. <form
  2.  action="upload.asp" method="post" enctype="multipart/form-data">
Notice the "enctype" attribute. If you don't have this attribute set to "multipart/form-data" then only the name of the file will be sent to the handler, in my case named "upload.asp ". Then of course you need an input of type="file" to accept the upload:
Expand|Select|Wrap|Line Numbers
  1. <input type="file" name="myFileToUpload" accept="image/*">
Notice the optional "accept" attribute which you may use to filter out unacceptable file types. I have set this to accept only files with image MIME-types. This can of course be expanded or omitted completely. finish off your form in any other way you want, then continue on to the next step.

Step 2: Opening binary data posted through your form
Unlike regular form inputs with which you have likely worked in the past, files are sent as binary data and can't be manipulated exactly as a string. Also, different browsers send these files in slightly different ways, so it is probably easiest to open up all of the data posted and search through it to find how the different inputs are separated, then try to figure out which is the file. Notice that as you work with binary data, you use functions that look a lot like string manipulation functions except they all end with the letter "B". They work just the same, but they are meant to handle binary data. Try this:
Expand|Select|Wrap|Line Numbers
  1. <%
  2. Dim posi, allData, delimiter, newLineB
  3.  
  4. 'put the whole form posted into "allData"
  5. allData = request.BinaryRead(Request.TotalBytes)
  6.  
  7. 'find the first new line character in allData
  8. newLineB = chrB(13) & chrB(10)
  9. posi = instrB(1, allData, newLineB)
  10.  
  11. 'find the string which separates the different inputs
  12. delimiter = midB(allData, 1, posi-1)
  13.  
  14. 'remove first delimiter and add a new line character to the end
  15. allData = midB(allData, posi + 2, lenB(allData) - lenB(delimiter) - 2 - 4)
  16. allData = allData & newLineB %>
Step 3: Find the file data:
What you now have is a variable named 'delimiter' which holds the separator the browser used to separate different form inputs (When I tested this, I used firefox and I wrote this variable after translating it to text. It turned out to be a long series of dashes followed by a 13-digit number. I have no idea what it means) and one called "allData" which has all of the rest of the data posted to the handler. If you were to translate this data to a string and write it to the screen it would look something like this:
Expand|Select|Wrap|Line Numbers
  1. Content-Disposition: form-data; name="myTextInput"
  2.  
  3. hello world
  4. -----------------------------4564239462453
  5. Content-Disposition: form-data; name="myFileToUpload"; filename="pic.jpg"
  6. Content-Type: image/jpeg
  7.  
  8. *** a whole bunch of nonsense characters representing all the binary data of the file ***
  9. -----------------------------4564239462453
  10. Content-Disposition: form-data; name="submit"
  11.  
  12. submit
  13. -----------------------------4564239462453--
So, how do I look through this? First notice that the first line of each input is the content disposition. this includes the file name, so don't throw it away. The second line lists the content type, but it is blank unless this input is a file. So I'm going to scroll through the inputs and discard them unless this second line has a content type. I'm going to use one function which converts binary data to the equivalent ascii characters, and a subroutine which saves the file.
Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  2.          "http://www.w3.org/TR/html4/loose.dtd">
  3.  
  4. <HTML><head><title>asp uploader</title></head><body>
  5.  
  6. <%
  7. 'find the file input, discard all others
  8. dim lstart, lfinish, disposition, fileType, content
  9. do while lenB(allData) > 0 'we're going to whittle allData down to nothing
  10.     lstart = 1
  11.     lfinish = instrB(1, allData, newLineB)
  12.  
  13.     disposition = converter(midB(allData, lstart, lfinish - lstart))
  14.     lstart = lfinish + 2
  15.  
  16.     If chr(ascB(midB(allData, lstart, 1))) = "C" then 'this input is a file
  17.         lfinish = instrB(lstart, allData, newLineB & newLineB)
  18.         'search for 2 new line characters, meaning the end of the
  19.         'content-type, saves it as fileType
  20.         fileType = trim(converter(midB(allData, lstart, lfinish - lstart)))
  21.  
  22.         'set the rest of this input as 'content'
  23.         posi = instrB(allData, newLineB & delimiter & newLineB)
  24.         content = midB(allData, lfinish + 4, posi-lfinish-4) 
  25.  
  26.         'display data for the file
  27.         response.write "<b>Content Disposition</b><br>" & vbNewLine
  28.         response.write disposition
  29.         response.write "<br>" & vbNewLine
  30.         response.write "<b>Content Type</b><br>" & vbNewline
  31.         response.write fileType
  32.         response.write "<br>" & vbNewLine
  33.         response.write "<b>Content</b><br>"
  34.  
  35.         'save file AND display it as either an <img> or <textarea>
  36.         saveFile content, disposition, fileType
  37.  
  38.         Response.Write "<br>"
  39.         Response.Write "<br>"& vbNewLine
  40.     End If
  41.  
  42.     'find the next delimiter in order to cut the first input from allData
  43.     posi = instrB(1, allData, newLineB & delimiter & newLineB)
  44.     allData = midB(allData, posi + 2 + lenB(delimiter) + 2)
  45. Loop
  46.  
  47.     Function converter(toConvert)
  48.         Dim output
  49.         Dim x
  50.  
  51.         x = 1
  52.         output = ""
  53.         'convert one character at a time to Ascii and add it to the output
  54.         do while x <= lenB(toConvert)
  55.             output = output & chr(ascB(midB(toConvert, x, 1)))
  56.             x = x + 1
  57.         loop
  58.  
  59.         converter = output
  60.     end function
  61.  
  62.     sub saveFile(content, disp, typ)
  63.         dim objFSO, objTXT, path, fileName
  64.  
  65.         'build the path to save the file
  66.         path = request.serverVariables("appl_physical_path") & "temp"
  67.  
  68.         'sometimes the filename has "\" which affects how I save it
  69.         if instr(disp, "\") > 0 then
  70.             fileName = mid(disp, instrRev(disp, "\"), len(disp)-instrRev(disp, "\"))
  71.         else
  72.             fileName = "\" & mid(disp, instr(disp, "filename=")+10, len(disp)-instr(disp, "filename=")-10) 
  73.         end if
  74.         path = path & fileName
  75.  
  76.         'save file with normal FSO and textStream methods
  77.         set objFSO = server.createObject("scripting.fileSystemObject")
  78.         set objTXT = objFSO.openTextFile (path, 2, True)
  79.         objTXT.write converter(content)
  80.         response.write "<br>(File saved as: " & path & ")<br>" & vbNewLine
  81.  
  82.         'display the file
  83.         if left(typ, 19) = "Content-Type: image" then 'file is an image
  84.             'write an image tag to the browser
  85.             response.write "<img src='/temp" & fileName & "'>"&vbNewLine
  86.         else 'file isn't an image
  87.             'write the contents of the file to a textarea in the browser
  88.             response.write "<textarea rows='10' cols='50' editable='false'>"
  89.             response.binaryWrite content
  90.             response.write "</textarea>" & vbNewline
  91.         end if
  92.     end sub
  93. %>
  94. </body>
Notice that I convert the content of the file to ascii characters and use a textstream to save it. Yes this does work for binary files. I tested it with several image files. There is a separate object called an ADO.STREAM which is supposed to be used for moving around binary files, but I couldn't get it to work for this application, and since the plain ol' textstream works OK, I will leave it like this.

Please give me any comments. I look forward to any feedback.

Jared
Aug 16 '07 #1
18 34801
mylo1968
8 New Member
Thank you,

for the code - it worked indeed, even was capable of processing multipple files. But only problem with it seems to be that it gets terribly slow with file sizes larger than 100 KB. And I could not process (upload) files larger than some 200 KB. - Also it seemed that there were differences between image types, even though I did not make any systematic research with this. Browsers I used were IE7 and FireFox, both worked approximately the same .

If you could make the script faster and being capable of uploading considerably larger files, it would be important piece of code indeed!

Regards,

Matti
Sep 17 '07 #2
jhardman
3,406 Recognized Expert Specialist
Matti,

hmm. I was aware that there was a file size limit, both with using the <input type=file> and on the server. Check your server's file upload limit (I'm not even sure where to look, but it's there somewhere) and I will research ways to get around this limitation in the script. I noticed that many of the pre-coded solutions I found on the web said that they had a way around this problem.

image type issues- this is most likely a display issue rather than an upload issue. The script just says to display any image file (whereas any other file type is not displayed) regardless of MIME type, and it is possible that some files of type "Image" will not display well in a browser. The display happens after the upload, so even if the display fails it is possible that the upload worked.

I will consider working on speed. I'll have to give it some thought. It's possible that the best way to improve speed would be to just switch to a compiled rather than scripted page, perhaps using ASP.NET

Thanks for your comments, and I will try to revise.

Jared
Sep 17 '07 #3
mylo1968
8 New Member
Jared,

I'll wait with interest in what you will come up with! - This area of asp-upload without third party components (or even with them) have produced very much headache for many asp-developers me including some times ago. So, I am eager to see if someone can really create a simple or even really readily workable solution for this. Well, I know, there already are many pure asp-upload-classes I have also tested, of which some work relatively well (with the exception usual of file size limit pronlem). But as you neetly put in your intro to your code, they are are tend to be very complex in comparison your relatively genious solution! - Inspiration for your work!

Regards,

Matti

Matti,

hmm. I was aware that there was a file size limit, both with using the <input type=file> and on the server. Check your server's file upload limit (I'm not even sure where to look, but it's there somewhere) and I will research ways to get around this limitation in the script. I noticed that many of the pre-coded solutions I found on the web said that they had a way around this problem.

image type issues- this is most likely a display issue rather than an upload issue. The script just says to display any image file (whereas any other file type is not displayed) regardless of MIME type, and it is possible that some files of type "Image" will not display well in a browser. The display happens after the upload, so even if the display fails it is possible that the upload worked.

I will consider working on speed. I'll have to give it some thought. It's possible that the best way to improve speed would be to just switch to a compiled rather than scripted page, perhaps using ASP.NET

Thanks for your comments, and I will try to revise.

Jared
Sep 19 '07 #4
kethireddy
4 New Member
Hi,
How to upload and display image in same page in asp.Can u suggest?
Sep 25 '07 #5
mylo1968
8 New Member
Here is fine asp-upload class and its explanation in case you do not have proper third order com-component available in your server.

http://www.stardevelop er.com/articles/display.html?ar ticle=200104250 1&page=1

And here you can download its source:
http://www.stardevelop er.com/downloads/zip/2001042501.zip

And after being capable of uploding a file into your server folder (uploaded) you can simply write:

<% response.write "<img src='/uploaded/" & fileName & "' width=100 height=200 >" %>

.. which will show your image file ( of course you can ignore width and height attributes)

Regards,

Matti

Hi,
How to upload and display image in same page in asp.Can u suggest?
Sep 25 '07 #6
kethireddy
4 New Member
Thxs for giving that sites.But i want with out hyperlink to display image.Onace we upload image immaediatly display image inthat same page,
http://www.stardeveloper.com/article...1042501&page=1

And here you can download its source:
http://www.stardeveloper.com/downloa...2001042501.zip

And after being capable of uploding a file into your server folder (uploaded) you can simply write:

<% response.write "<img src='/uploaded/" & fileName & "' width=100 height=200 >" %>

.. which will show your image file ( of course you can ignore width and height attributes)

Regards,

Matti
Oct 1 '07 #7
jhardman
3,406 Recognized Expert Specialist
Thxs for giving that sites.But i want with out hyperlink to display image.Onace we upload image immaediatly display image inthat same page,
this is either done with some advanced ajax or javascript, or some simple javascript which refreshes the page after uploading is done. This wouldn't necessarily be very tricky. I could probably get it to work, but it seems like more trouble than it's worth, and I'm not really a javascript expert, therefore, I won't reply with a code solution. However, the javascript forum might be able to come up with a concise solution.

Jared
Oct 1 '07 #8
einnor91
3 New Member
Hi Jared,
Im new in ASP.. i really like that code of yours in uploading file using asp.
Pls bear with me. I replicated your code and when i run it, it showed the input control and a button "browse". So i was abel to select a file. But how can I execute or submit it so that the file i selected will then be copied to the specific location.
Thanks!

einnor91
Oct 24 '07 #9
jhardman
3,406 Recognized Expert Specialist
Hi Jared,
Im new in ASP.. i really like that code of yours in uploading file using asp.
Pls bear with me. I replicated your code and when i run it, it showed the input control and a button "browse". So i was abel to select a file. But how can I execute or submit it so that the file i selected will then be copied to the specific location.
Thanks!

einnor91
Not a bad question. First understand that there need to be two different files at work (as I set up the code, that is. It is possible to do it all on one file, but I prefer to separate them). The first file contains the form that the user sees. I did not try to write the entire code for the form page since I figured
  • it is not necessary to use any kind of ASP to write the form, HTML or any WYSIWYG HTML editor can write this code for you
  • I figured that it is if not necessary, then highly recommended to be HTML proficient before attempting anything with ASP
I only mentioned a couple of things about the form page because the difficult part is the second page. The first page is pretty standard HTML and it should only give you trouble if you are not HTML proficient. I highly recommend learning HTML before you try to do much more with ASP.

That said, if you are not HTML proficient, how should you code the first page? Try this very basic form page:
Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  2.    "http://www.w3.org/TR/html4/loose.dtd">
  3. <HTML>
  4.    <HEAD>
  5.       <title>Generic From Page</title>
  6.       <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
  7.    </head>
  8.    <body>
  9.       <form action="upload.asp" method="post" enctype="multipart/form-data">
  10.          <input type="file" name="myFileToUpload" accept="image/*">
  11.          <input type="submit" name="submit" value="submit">
  12.       </form>
  13.    </body>
  14. </html>
  15.  
This basic form is set up to send a file to a page called "upload.asp " which should contain the script that accepts and saves the file. Let me know if this helps.

Jared
Oct 24 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

5
11131
by: Stephane | last post by:
Hello, I need to allow an end user to upload video files on a server and in the same time to put the file name and a few infos in a database. It must be very simple for the end user, and uploading with a browser in a form would be perfect since it allows to upload and fill a form in the same time. I'll have full control of the server (no max_size problem etc). The end user connexion is ADSL, the server is on a 100mb internet connexion.
6
10566
by: x. zhang | last post by:
Hi Guys, We know that we can use <input type=file ...> to upload one file per time to the server. My question is if there are some way to upload multiple files per time to the server. (Of course, we can use <input type=file ...> multiple times and then submit once. But this is not what I want, because we have to click "browse" button several times to select multiple files before submit in this way.) "Upload multiple files PER TIME", I...
1
5134
by: Susan | last post by:
Is it possible to use PHP with VBScript or JavaScript to upload multiple files. I'd like to automate the upload of a complete directory (not using FTP). I don't need a common form with several upload boxes. Thanks in advance, Susan
0
1367
by: deepaks85 | last post by:
Dear Friends, I am trying to upload multiple files. But I can't find why it is not working fine. Here is the code......... numfile.php <form method="POST" action="fileupload.php"> <p align="center"> <font face="Verdana" size="2">Number of files</font> <input type="text" class="text" name="numfiles" size="3" maxlength="3"><br>
12
2534
by: jodleren | last post by:
Hi I have an app, where I should upload files... Problem: when e.g. uploading 14MB (just 10MB) the page will load, then go back to the original page.... by some reason I cannot upload large files, larger than some 5 MB. I cannot get any information it looks like my server just reloads the original page.
4
1566
by: diptisk | last post by:
I want to upload files using ASP (not in binary format) on server .
43
9907
by: bonneylake | last post by:
Hey Everyone, Well this is my first time asking a question on here so please forgive me if i post my question in the wrong section. What i am trying to do is upload multiple files like gmail does. I found a script that does this on easycfm.com (Topic 13543). But anyway when i try to upload multiple files it will create multiple records in my database (like it should), but it wont upload multiple files. What ever file i choose to upload...
1
5155
by: helplakshmi | last post by:
Hi All, I wish you a Happy new year!!!.. My requirement is to upload an excel file using PHP and to update the data in MSSQL. For which i have designed a screen so that the user can browse 2 input files and update the database. html code for the same <table cellspacing="3" cellpadding="3" style="color:#0000b9; background-color:#d7deec; "> <tbody> <tr> <td>
0
2834
by: amskape | last post by:
hi Friends, I need to Upload some files in a Listing , by clicking corresponding Upload link, then a popup window will come with Browse option as Shown in attachment File. My actual need is upload files using that , but I can upload only 1 file there , I need to upload 1 to 5 files at a time based on need . How it can implement. I give my Working code here , in php Help me , if you know any other method to do same that's idea...
0
8888
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8752
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9401
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9176
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6702
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4519
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3221
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2635
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.